Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have method opt out of class-level AuthorizeAttribute?

I have an ApiController class with 10 public methods in it.

Out of those 10 methods, nine require an [Authorize(Roles="Admin")]. The one that doesn't, doesn't require any authorization.

If it weren't for that single method that doesn't require authorization, I would decorate the ApiController class with [Authorize(Roles="Admin")].

Instead of at the class level, I'm decorating all nine methods with the same [Authorize(Roles="Admin")] and not decorating that single method with an [Authorize(...)].

What I don't like about this is that I have to repeat the same [Authorize(Roles="Admin")] nine times.

Is there a way that I can instead still decorate the class with [Authorize(Roles="Admin")], and only decorate the single method that shouldn't have [Authorize(Roles="Admin")] with an attribute that means something like "don't apply the class-level action filter for this specific method"?

like image 818
core Avatar asked May 20 '15 14:05

core


1 Answers

You can use the [AllowAnonymous] attribute. I've done this on the Login action when a website was in preview, for example, so anybody can see the Login page, but nobody can see the rest of the site until they login. It was a simple workaround for a client :-)

In fact I even wrote a custom attribute which read the setting from the database, so I could put the website into "lockdown", if you get what I mean.

like image 129
Tom Chantler Avatar answered Oct 23 '22 18:10

Tom Chantler