我们要实现下面的效果,某个controller,只允许某几个角色访问(admin,user,document controller)

[MyAuthorize(Roles = "Admin,User,Document Controller")]
public class ClassController : Controller

首先, 登录的时候,要把用户的角色从DB拿出来,放到FormsAuthenticationTicket的UserData里. (假设我们使用Form认证)

 var roles = db.TN_Role.Where(t => t.User_Code.Equals(UserCode)).ToList();
if (roles == null)
return false;
else
{
foreach (var role in roles)
{
if (role.Company_ID.Equals(CompanyId) || role.Company_ID == null)
{
Session["Role"] = role.Role;
var authTicket = new FormsAuthenticationTicket(
,
UserCode,
DateTime.Now,
DateTime.Now.AddMinutes(), // expiry
false,
role.Role,
"/");
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
Response.Cookies.Set(new HttpCookie("Company", CompanyId.ToString())); return true;
}
}
return false;
}

重写AuthorizeAttribute

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
string cookieName = FormsAuthentication.FormsCookieName; if (!filterContext.HttpContext.User.Identity.IsAuthenticated ||
filterContext.HttpContext.Request.Cookies == null ||
filterContext.HttpContext.Request.Cookies[cookieName] == null
)
{
HandleUnauthorizedRequest(filterContext);
return;
} var authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(','); var userIdentity = new GenericIdentity(authTicket.Name);
var userPrincipal = new GenericPrincipal(userIdentity, roles); filterContext.HttpContext.User = userPrincipal;
base.OnAuthorization(filterContext);
}
}

这个方法的缺陷: 只适合权限比较简单的情况. 当新增角色或者角色改变时,只能修改每个Action对应的特性,当项目较大时工作量也很大.

05-11 19:52