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?

Answers


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"/>
</customErrors>

Need Your Help

Python how to grab certain number of lines after match

python printing lines text-files

Let's say I have an input text file of the following format:

how to read a CSV file in flex?

actionscript-3 flex flex4.5

I want to read a CSV file in FLex and display content of file on Datagrid. plzz provide solution...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.