Reputation: 25695
I am trying to stop a particular user in a particular role(say RoleA) from accessing a particular action. Anonymous users are allowed to access, but a user in RoleA is not allowed to access the action.
So I did something like this:
[AllowAnonymous]
[CustomAuthorize(Roles="RoleB,RoleC")]
public ActionResult MyAction(){
//irrelevant
}
But, the CustomAuthorize
action filter is never hit, when [AllowAnonymous]
is present.
So does [AllowAnonymous]
override [CustomAuthorize]
?
Upvotes: 6
Views: 3621
Reputation: 33857
To answer the question as asked (a little late, but hey might be useful for someone):
AllowAnonymous has the following description:
Represents an attribute that marks controllers and actions to skip the AuthorizeAttribute during authorization.
Thus adding this along with an authorize attribute will result in the authorization code not running at all.
This also has the effect that if you add this as an attribute on your controller as a whole (i.e. at class level), then adding individual Authorize attributes to actions on that controller will have no effect.
Upvotes: 10
Reputation: 25695
Well I ended up writing a deny attribute:
public class DenyUserAttribute : CustomAuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return !base.AuthorizeCore(httpContext);
}
}
Upvotes: 0
Reputation: 2126
A foolproof approach would be to code your own attribute and inherit it from the AuthorizeAttribute
. The implementation is trivial.
public class RestrictRoleAttribute : AuthorizeAttribute
{
public RestrictRoleAttribute()
{
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string[] roles = Roles.Split(',');
// Test if current user belongs into restricted role
foreach (string r in roles)
{
if (httpContext.User.IsInRole(r))
return false;
}
return true;
}
}
Usage:
[RestrictRole(Roles="RoleB,RoleC")]
public ActionResult MyAction(){
//irrelevant
}
Upvotes: 1
Reputation: 47774
This should be pretty easy to achieve.
Remove the [AllowAnonymous]
attribute and use your custom authorize attribute:
[CustomAuthorize]
public ActionResult MyAction(){
//irrelevant
}
and in your CustomAuthorize filter check if user belongs to 'RoleA', if yes then restrict access else allow access.
Upvotes: 2
Reputation: 113
I am not 100% sure but it might be the case. If you think about [Authorize] attribute which is on the controller level then the [AllowAnonymous] will override it so it takes a precedence over it.
Could you try to swap them with places so that [CustomAuthorize] will be on the top to see the result?
Regards
Upvotes: 0