MVC-登录并设置角色
1、新建一个类,设置角色:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace InfoData.Enum { public enum ERoles { Admin, User } public class ERolesHelper { public static string GetValue(ERoles role) { return role == ERoles.Admin ? "Admin" : "User"; } } public class ERolesAttribute : AuthorizeAttribute { //重载此方法,模拟自定义的角色授权机制 protected override bool AuthorizeCore(HttpContextBase httpContext) { //获得当前的验证cookie HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null || authCookie.Value == "") { return false; } else { FormsAuthenticationTicket authTicket; try { //对当前的cookie进行解密 authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { //和存入时的分隔符有关系,此处存入时的分隔符为逗号 var userRoles = authTicket.UserData.Split(new[] { ',' }).ToList(); var roles = Roles.Split(new[] { ',' }).ToList(); return roles.Any(x => userRoles.Contains(x)); } else { return false; } } catch { return false; } } } //没授权时跳到页面 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("/UserManage/Admin/Login"); ; } } }
2、登录代码:
DateTime now = DateTime.Now; string roles = ERolesHelper.GetValue(ERoles.Admin); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, now, now.AddMinutes(30), false, roles);//写入用户角色 string encryptedTicket = FormsAuthentication.Encrypt(authTicket);//对authTicket进行加密 SessionCookieHelper.SetCookie(FormsAuthentication.FormsCookieName, encryptedTicket, now.AddMinutes(30));
3、退出代码:
FormsAuthentication.SignOut(); SessionCookieHelper.ClearCookie(this.AdminCookieName);
4、Action或Controller添加:[ERolesAttribute(Roles = "Admin")]
如果允许匿名访问,添加:[AllowAnonymous]
[ERolesAttribute(Roles = "Admin")] public class AdminController : Controller { [AllowAnonymous] public ActionResult Login() { ViewBag.aaa = EncryptionHelper.DesEncrypt("xiaoming"); Dataprovider.Sys_AdminDAO.Logout(); return View(); } [AllowAnonymous] [HttpPost] public ActionResult Login(Admin_Login info) { if (ModelState.IsValid) { Dataprovider.Sys_AdminDAO.Login(info.UserName, info.Password); } return View(); } public ActionResult AdminList() { return View(); } }