asp.net mvc中Forms身份验证身份验证流程
验证流程
一、用户登录
1、验证表单:modelstate.isvalid
2、验证用户名和密码:通过查询数据库验证
3、如果用户名和密码正确,则在客户端保存cookie以保存用户登录状态:setauthcookie
1):从数据库中查出用户名和一些必要的信息,并把额外信息保存到userdata中
2):把用户名和userdata保存到 formsauthenticationticket 票据中
3):对票据进行加密 encrypt
4):将加密后的票据保存到cookie发送到客户端
4、跳转到登录前的页面
5、如果登录失败,返回当前视图
二、验证登录
1、在global中注册postauthenticaterequest事件函数,用于解析客户端发过来的cookie数据
1):通过 httpcontext.current.user.identity 判断用户是否登录(formsidentity,isauthenticated,authenticationtype)
2):从httpcontext 的request的cookie中解析出value,解密得到 formsauthenticationticket 得到userdata
2、角色验证
1):在action加入 authorize特性,可以进行角色验证
2):在 httpcontext.current.user 的 isinrole 方法进行角色认证(需要重写)
一、用户登录
1、设置web.config
设置重定向登录页面
<system.web> <authentication mode="forms"> <forms name="loginname" loginurl="/userinfo/login" cookieless="usecookies" path="/" protection="all" timeout="30"></forms> </authentication> </system.web>
注释掉
<modules> <!--<remove name="formsauthentication" />--> </modules>
2、登陆的验证中控制器
控制器中加“[authorize]”修饰的方法拒绝匿名。
public class userinfocontroller : controller //控制器 { //身份验证过滤器 [authorize] public actionresult index() { return view(); } }
控制器中登录
/// <summary> /// 用户登录 /// </summary> /// <returns></returns> public actionresult login() { return view(); } [httppost] public actionresult login(loginmodels login) { if (modelstate.isvalid) { var model = db.admininfo.firstordefault(a => a.adminaccount == login.adminaccount && a.adminpwd == login.adminpwd); if (model != null) { //存入票据(用户登录的时候去存信息,如果有信息直接去登录) var dtomodel = new users { id = model.id, adminpwd = model.adminpwd, adminaccount=model.adminaccount }; //调用 setauthcookie(dtomodel); //获取登录地址 var returnurl = request["returnurl"]; //判断登录地址是不是空值 if (!string.isnullorwhitespace(returnurl)) { return redirect(returnurl); } else { //return redirectitoaction return redirect("/home/index"); } } else { modelstate.addmodelerror("", "账号密码不对"); return view(login); } } else { modelstate.addmodelerror("", "输入的信息有误"); return view(login); }
对登录账号进行cookie
/// <summary> /// 对登录账号进行cookie /// </summary> /// <param name="model"></param> public void setauthcookie(users loginmodel) { //1、将对象转换成json var userdata = loginmodel.tojson(); //2、创建票据formsauthenticationticket formsauthenticationticket ticket = new formsauthenticationticket(2,"loginuser",datetime.now,datetime.now.adddays(1), false, userdata); //对票据进行加密 var tickeencrypt = formsauthentication.encrypt(ticket); //创建cookie,定义 httpcookie cookie = new httpcookie(formsauthentication.formscookiename, tickeencrypt); cookie.httponly = true; cookie.secure = formsauthentication.requiressl; cookie.domain = formsauthentication.cookiedomain; cookie.path = formsauthentication.formscookiepath; cookie.expires = datetime.now.add(formsauthentication.timeout); //先移除cookie,在添加cookie response.cookies.remove(formsauthentication.formscookiename); response.cookies.add(cookie); }
3、models中添加模型文件
public class loginmodels { /// <summary> /// 账号 /// </summary> [displayname("账号")] [required(errormessage = "账号不能为空")] public string adminaccount { get; set; } /// <summary> /// 密码 /// </summary> [displayname("密码")] [required(errormessage = "密码不能为空")] public string adminpwd { get; set; } }
4、views中 login 代码:
@using (html.beginform("login", "account", new { returnurl = viewbag.returnurl }, formmethod.post, new { @class = "form-horizontal", role = "form" }))
5、global设置
protected void application_authenticaterequest(object sender, eventargs e) { //1、通过sender获取http请求 // httpapplication app = new httpapplication();//实例化 httpapplication app = sender as httpapplication; //2、拿到http上下文 httpcontext context = app.context; //3、根据formsauthe,来获取cookie var cookie = context.request.cookies[formsauthentication.formscookiename]; if (cookie != null) { //获取cookie的值 var ticket = formsauthentication.decrypt(cookie.value); if (!string.isnullorwhitespace(ticket.userdata)) { //把一个字符串类别变成实体模型 var model = ticket.userdata.toobject<admininfoviewmodel>(); //var acount = model.adminaccount; //获取账号 context.user = new myformsprincipal<admininfoviewmodel>(ticket, model); //myformsprincipal.identity = new formsidentity(ticket); // myformsprincipal.userdata; } } }
6、退出登录
控制器中
/// <summary> /// 退出登录 /// </summary> public actionresult loginout() { //删除票据 formsauthentication.signout(); //清除cookie response.cookies[formsauthentication.formscookiename].expires = datetime.now.adddays(-1); response.cookies.remove(formsauthentication.formscookiename); return redirecttoaction("index", "home"); }
view跳转链接
@html.actionlink("安全退出","loginout","users")
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。