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:

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:

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?


You could also create an custom attribute which inherits from AuthorizeAttribute

Override the HandleUnauthorizedRequest method

You could specify in the web.config an url to show on the 401 case.

<customErrors mode="RemoteOnly" defaultRedirect="/Error/">
   <error statusCode="401" redirect="/AuthorizationFailed"/>

Need Your Help

FindWindowEx - Select textbox if there are several textboxes with same classname

c# findwindow

I want to use SendMessage/PostMessage to send some keys to an applications textbox. I used Microsoft Spyxx to get class name of this textbox. Now I have the problem that there are several textboxes...

Python convert WKT polygon to row wise points

python latitude-longitude points polygons wkt

"POLYGON ((12 13,22 23,16 17,22 24))",101,Something,100000