Show 404 error page after [Authorize] failure

落爺英雄遲暮 提交于 2019-12-21 04:49:19

问题


I have an action I want to restrict only to role "Admin". I did it like this:

[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)

After manually going under Controller/Edit/1 path I'm redirected to login page. Well, that isn't bad maybe, but I want to show 404 instead of it and try to stick using attributes for it. Is that possible?


回答1:


Is that possible?

Sure, you could write a custom authorize attribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Shared/401.cshtml"
        };
    }
}

and then use it:

[MyAuthorize(Roles = "Admin")]
public ActionResult Edit(int id)

Remark: you probably want to show a 401 or 403 page if the user is not authorized instead of 404 which is for file not found.




回答2:


In response to @Daniel's comment on my comment to @Darin's answer this is my implementation:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        string cookieName = FormsAuthentication.FormsCookieName;

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated ||
            filterContext.HttpContext.Request.Cookies == null ||
            filterContext.HttpContext.Request.Cookies[cookieName] == null
        )
        {
            HandleUnauthorizedRequest(filterContext);
            return;
        }

        var authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        string[] roles = authTicket.UserData.Split(',');

        var userIdentity = new GenericIdentity(authTicket.Name);
        var userPrincipal = new GenericPrincipal(userIdentity, roles);

        filterContext.HttpContext.User = userPrincipal;
        base.OnAuthorization(filterContext);
    }

    // Redirects unauthorized users to a "401 Unauthorized" page
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Shared/Error/401.cshtml"
        };
    }
}


来源:https://stackoverflow.com/questions/9503500/show-404-error-page-after-authorize-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!