ASP.NET MVC - How to show unauthorized error on login page?

后端 未结 7 2031
花落未央
花落未央 2020-11-28 02:58

In my ASP.NET MVC app, I have most controllers decorated with

[Authorize(Roles=\"SomeGroup\")]

When a user is not authorized to access som

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 03:26

    Ben Cull's method works well, but remember there are two AuthorizeAttribute classes - one in System.Web.HTTP (used by Web API), and the other in System.Web.Mvc. Ben's method uses the System.Web.Mvc class. For clarity, I suggest using the fully qualified path.

    If you're using Web API alongside MVC, you will need to implement two filters:

    public class AuthorizeRedirectMVCAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
    
            if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("~/Account/AccessDenied");
            }
        }
    }
    
    public class AuthorizeRedirectAPIAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);
    
            if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }
    }
    

    Note that asp.net will let you decorate your MVC controller with an API filter - it just won't work the way you expect, so keep your attribute names explicit.

提交回复
热议问题