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]
?
One of the new features in ASP.NET MVC 4 is the AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions.
The AllowAnonymous attribute in MVC is used to skip the authorization which is enforced by Authorization Filter in MVC. Now, run the application and navigate to /Home/NonSecured and you will see that it displays the page as expected and when you navigate to /Home/Secured, then it will redirect you to the Login page.
If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL.
Right-click on the solution and add a new class. Enter the class name and click on Add. Next Inherite Attribute, IAuthorizationFilter to CustomAuthorization class which has overridden the OnAuthorization method. The OnAuthorization Method has the AuthorizationFilterContext parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With