Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC 3: Inverse Authorize Attribute

I have a simple ASP.Net MVC 3 application that has some controller and a good few actions.

Now, as this is a user based application, most of the controller actions require the user to be authenticated. MVC handles this well with the built-in Authorize attribute which you can use to decorate controllers and/or actions individually.

The great thing is you can apply the attribute to just the controller and all actions for that given controller will have it applied too - lots of typing saved ;)

But I have one controller with, lets say, 10 actions. But I want one of the actions to not have the Authorize attribute applied.

Yes, I could apply the attribute to the other 9 and remove it from the controller which will do exactly what I need. But is there a way to keep it applied to the controller and just choose to exclude one of the actions?

Effectively, would want something like...

[!Authorize] or [NotAuthorize]

I know I could create a custom one that will do the job, but what I want to know is if there is a built-in way to do this? or do I have to apply the attribute to all 9 other actions?

like image 801
musefan Avatar asked Nov 03 '11 16:11

musefan


People also ask

How do I override an authorized attribute?

You could create a custom authorisation attribute inheriting from the standard AuthorizeAttribute with an optional bool parameter to specify whether authorisation is required or not. and for any controllers you don't want authorisation simply use the override with a 'false' - e.g.

How does Authorize attribute work in ASP.NET MVC?

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. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.


1 Answers

Note that a new attribute has been added in ASP.NET MVC 4.0 that does exactly that:
[AllowAnonymous]

like image 94
Xavier Poinas Avatar answered Nov 10 '22 09:11

Xavier Poinas