Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force only anonymous access to controller action?

I can use the [AllowAnonymous] attribute to permit a user to access a controller action, but is there an attribute to permit only anonymous users to an action? e.g. [AllowAnonymousOnly]

like image 893
Tarostar Avatar asked Apr 08 '15 11:04

Tarostar


People also ask

What attribute will ensure anonymous users can access a specific controller action?

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.

What is AllowAnonymous?

AllowAnonymous lets users who have not been authenticated access the action or controller. In short, it knows based on the token it receives from the client.

How do you use AllowAnonymous?

[AllowAnonymous] bypasses all authorization statements. If you combine [AllowAnonymous] and any [Authorize] attribute, the [Authorize] attributes are ignored. For example if you apply [AllowAnonymous] at the controller level, any [Authorize] attributes on the same controller (or on any action within it) are ignored.


1 Answers

No. It doesn't exist.

However, you can create it by creating your own attribute inheriting from the AuthorizeAttribute.

Here's an example.

Yours would look like:

public class AllowAnonymousOnlyAttribute : AuthorizeAttribute
{    
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // make sure the user is not authenticated. If it's not, return true. Otherwise, return false
    }
}
like image 189
André Pena Avatar answered Oct 29 '22 14:10

André Pena