Redirect Unauthorized Page Access in MVC to Custom View

一个人想着一个人 提交于 2019-11-29 22:35:25

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 worked 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. f.e. like this in the controller.

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

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

Note: It doesn't work the same with 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.

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!

Probably best way to handle this is to create an additional action filter, that redirects the user to the specified error page if he does not belong to the specified role. So, this methods will have both filters applied: [Authorize] (with no roles) to protect from unauthenticated users and redirecting them to the Login Page. And your custom Attribute with the roles. Code SIMILAR to this (not tested):

public class RoleFilterAttribute : ActionFilterAttribute
{
    public string Role { get; set; }
    public override void OnActionExecuting(ActionExecutingContext ctx)
    {
        // Assume that we have user identity because Authorize is also
        // applied
        var user = ctx.HttpContext.User;
        if (!user.IsInRole(Role))
        {
            ctx.Result = new RedirectResult("url_needed_here");
        }
    }
}

Apply both [Authorize] and [RoleFilter] to the actions...

Hope this helps!

I think you should create your own Authorize filter attribute which inherit of the default Authorize filter

public class CustomAuthorize: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
       filterContext.Result = new HttpUnauthorizedResult(); // Try this but i'm not sure
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!