Redirect Unauthorized Page Access in MVC to Custom View

user2739418 picture user2739418 · Feb 27, 2014 · Viewed 59.3k times · Source

I have an MVC website in which access is based on various Roles. Once a user logs into the system they can see navigation to the pages for which they are authorized. However, some users may still try to access pages using a direct URL. If they do, the system automatically redirects them to the Login Page. Instead of the Login Page I want to redirect them to another view (Unauthorized).

Web.Config has the following entry:

    <customErrors mode="On">
      <error statusCode="401" redirect="~/Home/Unauthorized" />
      <error statusCode="404" redirect="~/Home/PageNotFound" />
    </customErrors>
    <authentication mode="Forms">
<forms name="Development" loginUrl="~/Account/Login" cookieless="UseCookies" timeout="120"></forms>
    </authentication>

I have registered these routes in Global.asax.cs as well.

routes.MapRoute(
    name: "Unauthorized",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Unauthorized", id = UrlParameter.Optional }
   );


routes.MapRoute(
    name: "PageNotFound",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "PageNotFound", id = UrlParameter.Optional }
    );

Will it be enough?

Answer

The Vojtisek picture The Vojtisek · Aug 18, 2014

After some research I think the easiest answer to this problem is just creating custom authorize, very similar to the one by jbbi (but that one didn't work since the "new HttpUnauthorizedResult()" is internaly automatically redirecting to the login - at least in mvc 5 with identity)

public class CustomAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            //if not logged, it will work as normal Authorize and redirect to the Login
            base.HandleUnauthorizedRequest(filterContext);

        }
        else
        {
            //logged and wihout the role to access it - redirect to the custom controller action
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
        }
    }
}

and the usage is the same as the default Authorize:

[CustomAuthorize(Roles = "Administrator")]

Then, just to do things right, don't forget to send out the Http code of the error page. e.g like this in the controller.

public ActionResult AccessDenied()
{
    Response.StatusCode = 403;
    return View();
}

It's easy, it works and even I (a .net mvc rookie) understand this.

Note: It doesn't work the same with a 401 code - it will always take over the 401 and internaly redirect it to the login. But in my case is, by definition, the 403 also fitting.