2

Closed

Add IAllowAnonymous interface and check for this in the skipAuthorization section of AuthorizeAttribute

description

AuthorizeAttribute contains code that checks for the existence of AllowAnonymousAttribute, which allows holes to be punched in to an otherwise fully protected controller. However, this hard coupling makes it difficult to create additional functionality.

For an example as to why this functionality would be useful, please see this post: http://stackoverflow.com/questions/13714250/single-responsibility-principle-in-mvc-controllers-critique-required

I would like to be able to combine my proposed AnonymousOnlyAttribute with the functionality of AllowAnonymousAtrribute, but cannot do it without subclassing AllowAnonymousAttribute.

The ideal solution would be for me to 'implement' the empty IAllowAnonymous interface. Then, if AuthorizeAttribute checked for this interface during the skipAuthorization stage, it would allow more flexibility, and it would remove the need for me to include both the AllowAnonymous and AnonymousOnly attributes. (Afterall, AnonymousOnly kind of assumes AllowAnonymous!)
Closed Sep 20, 2013 at 10:52 PM by eilonlipton
While this seems like an interesting suggestion, we are not seeing enough demand for this.

We recommend deriving from AuthorizeAttribute and overriding OnAuthorize. In the overridden method you could add your own custom logic and if that logic passes, call base.OnAuthorize() to fall back to the default behavior.

Thanks,
Eilon

comments

gforce0803 wrote Dec 20, 2012 at 10:45 AM

Why not just write a simple AllowUnauthorisedOnlyAttribute and check your the user is not authenticated? and return false if the user is authenticated.

simongoldstone wrote Dec 20, 2012 at 11:16 AM

I don't think that will work. The AnonymousOnlyAttribute I've already written cannot influence the behaviour of the AuthorizeAttribute. If AuthorizeAttribute is applied to the whole class, I cannot punch a hole in it with anything other than the AllowAnonymous attribute.

It's not a major problem, in that I can decorate my method with BOTH AnonymousOnlyAttribute AND AllowAnonymous but it's just inconvenient.

And since the MVC allows such much extension and flexibility, I think it's a valid argument to remove the coupling on a concrete class, and instead look for IAllowAnonymous in the AuthorizeAttribute instead.