C# – How to redirect to a not-authorized page instead of the login page when the user is already logged in

asp.net-mvccnet

How do I set my Authorize(Roles="blah") token to redirect to a "You're not authorized to do this" when a user is already logged in but isn't in the correct role? Currently it redirects to the login page which isn't what we're after. We feel that it's confusing for the user to be redirected to this page as they're already logged in. In the event however they're not logged in, it should redirect to the login page.

Best Answer

The way AuthorizeAttribute is designed is that it will first look if the user is authenticated and then look if he is in role. If any of these conditions aren't satisfied it will simply return return a HttpUnauthorizedResult which in turn will set the response code to 401. To achieve what you want you will need to implement your own IAuthorizationFiler.