1.登录的代码
1 [HttpPost] 2 ????????public ActionResult Index(User entity) 3 ????????{ 4 ????????????User user = GetUser(entity.Name, entity.Password); 5 ????????????if (user != null) 6 ????????????{ 7 ????????????????FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 8 ????????????????????????????1, 9 ????????????????????????????user.UserID.ToString(),10 ????????????????????????????DateTime.Now,11 ????????????????????????????DateTime.Now.AddMinutes(30),12 ????????????????????????????false,13 ????????????????????????????user.RoleNames.XJoin(","));14 ????????????????string encTicket = FormsAuthentication.Encrypt(authTicket);15 ????????????????HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];16 ????????????????if (cookie == null)17 ????????????????{18 ????????????????????cookie = new HttpCookie(FormsAuthentication.FormsCookieName);19 ????????????????}20 ????????????????cookie.Value = encTicket;21 ????????????????HttpContext.Response.AppendCookie(cookie);22 ????????????????return RedirectToAction("Index", "Test");23 ????????????}24 ????????????return View();25 ????????}
FormsAuthenticationTicket的user.RoleNames.XJoin(",")是我自己写的扩展方法,表示用","分隔开的字符串。
生成票据
2.Global.asax中的代码
1 protected void Application_AuthenticateRequest(Object sender, EventArgs e) 2 ????????{ 3 ????????????if (HttpContext.Current.User != null) 4 ????????????{ 5 ????????????????if (HttpContext.Current.User.Identity.IsAuthenticated) 6 ????????????????{ 7 ????????????????????if (HttpContext.Current.User.Identity is FormsIdentity) 8 ????????????????????{ 9 ????????????????????????FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;10 ????????????????????????FormsAuthenticationTicket ticket = id.Ticket;11 ????????????????????????string userData = ticket.UserData;12 13 ????????????????????????string[] roles = userData.Split(‘,‘);14 ????????????????????????HttpContext.Current.User = new GenericPrincipal(id, roles);15 ????????????????????}16 ????????????????}17 ????????????}18 ????????}
给用户票据的时候在里面加了一个字符串的角色信息,比如“Administrator”,当一个请求过来的时候asp.net会有一个Application_AuthenticateRequest的事件,专门用于用户认证授权,在这个事件中我们只需要将这个字符表达的角色重建给用户就可以,我们在Global.asax的Application_AuthenticateRequest方法中增加如下代码
3.Controller中的代码
1 ????[Authorize(Roles="sysadmin")] 2 ????public class TestController : Controller 3 ????{ 4 ????????public ActionResult Index() 5 ????????{ 6 ????????????return View(); 7 ????????} 8 ????}
Roles参数可以包含多个Role,比如([Authorize(Roles="sysadmin,conadmin")]),Authorize属性页可以具体控制到某个action,只需要将其写到对应Action方法的属性上即可。
4.webConfig中的代码
1 <authentication mode="Forms">2 ??????<forms loginUrl="~/Login/Index" timeout="2880" />3 </authentication>
MVC 基于FormsAuthentication 方式的权限验证
原文地址:http://www.cnblogs.com/sjqq/p/7653269.html