Search code examples
asp.net-mvcauthorizationunauthorized

Redirect Unauthorized Page Access in MVC to Custom View


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?


Solution

  • With following change it is working

    public class CustomAuthorize : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //filterContext.Result = new HttpUnauthorizedResult(); // Try this but i'm not sure
              filterContext.Result = new RedirectResult("~/Home/Unauthorized");
        }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (this.AuthorizeCore(filterContext.HttpContext))
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                this.HandleUnauthorizedRequest(filterContext);
            }
        }
    
    }
    

    And then applying on Controller or Action as below:

    [CustomAuthorize(Roles = "Admin")]
    

    With above approach I need to revisit all the controller/actions and change the Authorized attribute! Also some testing will be needed.

    I am still not sure why Web.Config route not working as same has been explained in MVC Documentation. May be something has changed in MVC 4!