I have defined a custom Authorization Attribute and it is automaticly applied to all actions in the solution.
In its OnAuthorize method i use the IsDefined method to find if another attribute is defined but it seems that it always returns false.
Edit: the AuthorizeAttr attribute is set in the RegisterGlobalFilters function in Global.asax and the Anon attribute is marked directly above the actions that doesn´t need authorization.
Here is my code:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class Anon : Attribute { }
public class Role : Attribute
{
public int Id;
public Role(int id)
{
Id = id;
}
}
public class AuthorizeAttr : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!(filterContext.ActionDescriptor.IsDefined(typeof(Anon), false)) || !(filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(Anon), false)))
{
Procurement.User u = MvcApplication.GetCurrentUser(filterContext.HttpContext);
if (u == null || !u.enabled)
filterContext.Result = new RedirectResult("/Session/Login?msg=You must log in to use this site.&ReturnUrl=" + filterContext.RequestContext.HttpContext.Request.RawUrl);
if (filterContext.ActionDescriptor.IsDefined(typeof(Role), false))
{
object[] criterias = filterContext.ActionDescriptor.GetCustomAttributes(typeof(Role), false);
bool authorized = true;
for (int x = 0; x < criterias.Length; x++)
{
if (((Role)criterias[x]).Id > u.roleId)
{
authorized = false;
break;
}
}
if (!authorized)
{
ContentResult C = new ContentResult();
C.Content = "<h1><b>The resource is unavailable!</b></h1>";
filterContext.Result = C;
}
}
}
}
}
In boolean algebra the negation of
is:
So you probably want an
&&condition:or if you want
||:Obviously the first is by far more readable.