标签:
1、新建一个类,设置角色:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.Controllers; using System.Web.Mvc; using System.Web.Security; namespace Soft.Dataprovider { public enum ESoftRoles { Admin, User } public class ESoftRolesHelper { public static string GetValue(ESoftRoles role) { string roleType = "User"; if (role == ESoftRoles.Admin) { roleType = "Admin"; } else { roleType = "User"; } return roleType; } } public class ESoftRolesAttribute : AuthorizeAttribute { //重载此方法,模拟自定义的角色授权机制 protected override bool AuthorizeCore(HttpContextBase httpContext) { //获得当前的验证cookie HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null || authCookie.Value == "") { return false; } FormsAuthenticationTicket authTicket; try { //对当前的cookie进行解密 authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch { return false; } if (authTicket != null) { //和存入时的分隔符有关系,此处存入时的分隔符为逗号 var userRoles = authTicket.UserData.Split(new[] { ‘,‘ }).ToList(); var roles = Roles.Split(new[] { ‘,‘ }).ToList(); return roles.Any(x => userRoles.Contains(x)); } return false; } //没权限时跳到页面 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("/Account/MyAuth"); ; } } }
2、登录代码:
string roles = ESoftRolesHelper.GetValue(ESoftRoles.Admin); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), false, roles);//写入用户角色 string encryptedTicket = FormsAuthentication.Encrypt(authTicket);//对authTicket进行加密 SessionCookieHelper.SetCookie(this.AdminCookieName, encryptedTicket, DateTime.Now.AddHours(2)); info.CountOfLogin += 1; info.LastLoginDate = DateTime.Now; entity.Configuration.ValidateOnSaveEnabled = false; entity.SaveChanges(); entity.Configuration.ValidateOnSaveEnabled = true;
3、退出代码:
FormsAuthentication.SignOut(); SessionCookieHelper.ClearCookie(this.AdminCookieName);
4、Action或Controller添加:
[ESoftRolesAttribute(Roles = "Admin")]
如果允许匿名访问,添加:
[AllowAnonymous]
标签:
原文地址:http://www.cnblogs.com/yaosuc/p/4530681.html