How do I serve up an Unauthorized page when a user is not in the Authorized Roles?

前端 未结 5 765
眼角桃花
眼角桃花 2020-12-04 15:54

I am using the Authorize attribute like this:

[Authorize (Roles=\"Admin, User\")]
Public ActionResult Index(int id)
{
    // blah
}
5条回答
  •  死守一世寂寞
    2020-12-04 16:11

    Just override the HandleUnauthorizedRequest method of AuthorizeAttribute. If this method is called, but the user IS authenticated, then you can redirect to your "not authorized" page.

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Area = "", Controller = "Error", Action = "Unauthorized" }));
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
    }
    

提交回复
热议问题