Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AllowAnonymous override AuthorizeAttribute

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]?

like image 717
Aniket Inge Avatar asked Apr 09 '14 07:04

Aniket Inge


People also ask

What is the functionality of AllowAnonymous directive?

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.

What is the use of AllowAnonymous in MVC?

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.

Which attribute is used to override required authentication?

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.

How do I override an authorized attribute in .NET core?

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.


1 Answers

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.

like image 115
Paddy Avatar answered Jan 03 '23 14:01

Paddy