Search code examples
asp.net-mvc-3windows-authenticationroleprovider

How to handle authorisation failure in MVC3


I'm building an internal (intranet) MVC3 application using Windows Authentication and a custom role provider. The authentication and role provider work okay, as long as the the user has the role requested.

For example, I have a UserContoller which allows the user of the application to manage user accounts within the application. Obviously i want to restrict access to this controller.

If I do this:

[Authorize]
public class UserController : Controller
{
    ...
}

then the Windows Authentication works fine, and the user is transparently logged in. However, I want to restrict the controller to a specific group of users. So I do this:

[Authorize(Roles="UserAdmin")]
public class UserController : Controller
{
    ...
}

If the list of roles returned by my role provider includes "UserAdmin", then everything is fine and the user gets access to the controller.

However, if the user is not in the role then the browser (tested on IE8 and FF10) prompts for credentials. If that is cancelled then the server returns a 401 error page.

So my question after all of that is, how do I handle the situation where the user is not in the requested role, and return him to the application's home action, or some other action to provide a user-friendly message?


Solution

  • You could also create an custom attribute which inherits from AuthorizeAttribute

    Override the HandleUnauthorizedRequest method