MVC4商城项目二:用户身份验证的实现
用户身份验证,依赖于 forms 身份验证类:FormsAuthentication,它是一串加密的cookie 来实现对控制器访问限制和登陆页面的访问控制。它在浏览器端是这样子的:
需求:我们要实现对用户中心只有登录的用户才能访问,如果没登录就跳转到登录页面,其它页面都可以访问:
首先来看登录控制器的代码:
UserDto user = UserService.GetUserById(Convert.ToInt32(msg.Msg)); //为提供的用户名提供一个身份验证的票据 FormsAuthentication.SetAuthCookie(user.UName, true, FormsAuthentication.FormsCookiePath); //把用户对象保存在票据里 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, user.UName, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), false, JsonConvert.SerializeObject(user)); //加密票据 string hashTicket = FormsAuthentication.Encrypt(Ticket); HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket); Response.Cookies.Add(userCookie); //被限制要登录的页面会在url上带上上一访问的页面 if (Request["ReturnUrl"] != null || Request["ReturnUrl"]!="") { return Redirect(HttpUtility.UrlDecode(Request["ReturnUrl"])); }
web.config 的配置,loginUrl为指定的登录页面
<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication> <authorization> <deny roles="controler"/> <allow users="*"/> </authorization>
在控制器加入[Authorize]注解,就可以控制用户的访问了,
[Authorize] public ActionResult Index() { UserDto user = UserService.GetUserById(1); return View(user); }
当然也可以注解的属性来控制不同角色和不同用户的权限:
[Authorize(Roles = "controler")] public ActionResult Index() { UserDto user = UserService.GetUserById(1); return View(user); } [Authorize(Users = "admin")] public ActionResult Order() { return View(); }
注销操作:清除cookie
//注销 public ActionResult LoginOut() { FormsAuthentication.SignOut(); return RedirectToAction("Index", "Home"); }
如果想更详细的了解forms身份验证请 点 http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html