if (账号密码验证成功) { //登陆成功 Session["User"] = account; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, account.ID.ToString(), DateTime.Now, DateTime.Now.AddDays(1), true, "1,5,7", //可以存储role "/" ); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); cookie.HttpOnly = true; HttpContext.Response.Cookies.Add(cookie); return RedirectToAction("Index", "Admin"); }
需要使用的Role验证的地方
if (User.IsInRole("1")) { //用户拥有“1”角色权限 }
在需要,验证的Controller、Action上面添加注解属性,比如这个Action 只允许RoleID 为包含1或2或3的访问,而当前用户RoleID为(1、5、7)就是用户有权访问了。
[Authorize(Roles="1,2,3")] public ActionResult Index() { return View(); }
需要配置web.config
<authentication mode="Forms"> <forms loginUrl="~/Login/Index" timeout="2880" /> </authentication> <roleManager enabled="true" defaultProvider="CustomRoleProvid"> <providers> <clear/> <add name="CustomRoleProvid" type="HotelShow.CustomRoleProvider"/> <!--自定义获取Role的方法--> </providers> </roleManager>
CustomRoleProvider类的需要继承RoleProvider,实现GetRolesForUser方法
public override string[] GetRolesForUser(string username) { var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookie.Value); string role = ticket.UserData; return role.Split(','); }