house9

random code and what not

Fixing asp.net MVC AuthorizeAttribute

With very little code we can fix asp.net MVC AuthorizeAttribute
What problems does it have? Too much redirection.

  • When making ajax calls a HTTP 401 (Unauthorized) would be better than a redirection
  • If I am already logged in but access a secure resource (controller / action) redirecting to the login page is far from ideal, an access denied view makes more sense
When is the built in redirection appropriate? When making standard HTTP request and the user is not authenticated.

it turns out it is relatively easy to fix these issues
  • inherit AuthorizeAttribute
  • override HandleUnauthorizedRequest
#1: Ajax request should not return redirection / html response

if the user cannot authorize an action and the request is made via ajax we don’t want 200 or 302 response codes

we do want 401 Unauthorized, but we have to settle for a 403 Forbidden

The code to fix this

#2: Authenticated users should not redirect to the login page, they should get an Access Denied page
The code to fix this

Turns out very little code is needed - but seems like some of this should just be built in? Using the 401 response won’t work because the asp mvc framework must be picking that up later on and forcing the redirection to the login page, the 403 is not ideal but it is effective.

The code for our class - AuthorizeFor


Usage of our AuthorizeFor attribute


Resources