views:

67

answers:

2

In the ASP.NET MVC site I am building, I have some methods where the users who use them have to be in a certain role (as it happens, if they're not, it means that they're suspended from the site). To accomplish this, I'm using the [Authorize(Roles="RoleName")] attribute without any difficulties.

However, I don't quite understand what happens to users who don't pass that [Authorize] check? What are they shown?

I want to redirect suspended users to a different Action if they try to use these methods. For now, I've been using a blank [Authorize] attribute (without any roles specified) and then checking in the Action code whether the user is part of the Role or not.

My approach feels like a code smell to me. Is it possible to specify what to show to a user (or where to redirect them to) if they don't pass the [Authorize] check?

+4  A: 

As stated on the AuthorizeAttribute MSDN page:

If an unauthorized user tries to access a method that is marked with the Authorize attribute, the MVC framework returns a 401 HTTP status code. If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.

If you're using forms authentication and want to redirect to the login page, you have nothing to do. Otherwise implement your own IAuthorizationFilter to do the redirection.

Edit: see this blog post that basically reimplement the AuthorizeAttribute manually, with custom redirection.

Julien Lebosquain
How does it redirect the user to the login page if the user is already logged in (but doesn't have sufficient privileges)? Also, how can I implement my own IAuthorizationFilter? Thanks!
Maxim Zaslavsky
+1  A: 

If you don't want to implement your own IAuthorizationFilter I believe you should be able to override the default behavior of the Authorize attribute. Just inherit and override the HandleUnauthorizedRequest method. Granted you'll still need a way to determine if the user failed due to not being logged in vs not having the right permissions. It may be cleaner just to write your own authorization filter.

Ryan