我正在尝试将Enum
用于注释[Authorize]
。我已经配置但它仍然不起作用,安全策略允许访问。
我没有创建我的Enum
数字示例:Administrator = 1
或类似的东西,我刚刚使用描述Administrator, Manager, Common
创建。我不会将数字创建为索引,只是想按照我所示的描述进行创建。
我该如何解决这个问题?
枚举
public enum RoleType{
Administrator,
Manager,
Common
};
AuthorizeAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Method, AllowMultiple = false)]
public class PermissionFilter : AuthorizeAttribute{
public RoleType Roles {get;set;}
protected override bool AuthorizeCore(HttpContextBase httpContext){
if (httpContext == null)
throw new ArgumentNullException("httpContext");
if (!httpContext.User.Identity.IsAuthenticated)
return false;
//get the Session of User
User user = httpContext.Session["User"] as User;
RoleType role = user.role;
if (((Roles & role) != role))
return false;
return true;
}
public override void OnAuthorization(AuthorizationContext filterContext){
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
filterContext.HttpContext.Response.Redirect("/Home/accessDenied");
}
}
方法
[PermissionFilter(Roles= RoleType.Manager)]
public ActionResult viewAllAdmin(int? pagina, String nome){
}
答案 0 :(得分:1)
解决了这个问题。
我做了
<强> AuthorizeAttribute 强>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Enum | AttributeTargets.Method, AllowMultiple = false)]
public class PermissionFilter : AuthorizeAttribute{
public RoleType[] Roles;
public PermissionFilter(params RoleType[] roles){
Roles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext){
if (httpContext == null)
throw new ArgumentNullException("httpContext");
if (!httpContext.User.Identity.IsAuthenticated)
return false;
try{
Usuario usuario = httpContext.Session["Usuario"] as Usuario;
RoleType role = usuario.role;
Boolean contain = Roles.Contains<RoleType>((RoleType)role);
Console.WriteLine("Contem Role: " + contain);
if (!Roles.Contains<RoleType>((RoleType)role)){
return false;
}
return true;
}catch (Exception e){
Debug.WriteLine("PermissionFilter AuthorizeCore: " + e.Message);
return false;
}
}
public override void OnAuthorization(AuthorizationContext filterContext){
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
filterContext.HttpContext.Response.Redirect("/Home/acessoNegado");
}
}
方式强>
[PermissionFilter(RoleType.Administrator, RoleType.Manager)]
public ActionResult viewAllAdmin(int? pagina, String nome){
}
然后,它运作正常!