4

I have an MVC 4 intranet app that I created using Visual Studio 2012. I used WindowsAuthentication and it authenticates users as expected. On some actions I restricted users to certain roles using Authorize attribute. When a user clicks on a link that invokes a controller action for which the user has no authorization it pops up an 'Authentication Required' dialogue. When I login with an account that has no authorization it keeps on popping up the dialogue. Instead I would like this:

  1. When a user is not authorized to access the page, pop up the dialogue as currently doing.
  2. When the user inputs a login that is valid but not authorized to access the page redirect to another page saying the access is forbidden.

How do I go about doing this? As a relevant information I customized the role provider using the approach discussed here

1 Answer 1

3

For this you will need a Custom Authorization to handle the unauthorized situations yourself.

You will need a method like this:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this got me started in the right direction. Instead of standard error I am doing a redirect to a custom page that also provides a link to login as another user. I used the approach from the following link for doing that: morgantechspace.com/2013/08/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.