ASP.NET Identity发出302 Found响应,将所有未经授权的请求重定向到"登录"页面,包括权限不足的已验证请求。将经过身份验证的用户重定向到登录页面是一种令人困惑的用户体验。
如何拦截/停止/取消已验证用户的重定向,并发出403禁止响应(从而显示我的自定义403页面(?未经身份验证的用户应该继续看到标准行为。
我尝试在CookieAuthenticationMiddleware
之前和之后添加一个简单的自定义Owin中间件,但不知道如何识别未经授权的请求。
您需要一个具有类似代码的自定义身份验证过滤器:
public abstract class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
//Intercept results where person is authetnicated but still doesn't have permissions
if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.TempData["ErrorMessage"] = "Sorry, you are logged in but you have attempted to access a page that you don't have permissions to.";
//TODO need to set up a route that points to your custom page, call that route RestrictedAccess
filterContext.Result = new RedirectToRouteResult("RestrictedAccess", new RouteValueDictionary());
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
然后,您需要将[MyAuthorise]
属性应用于控制器,而不是[Authorise]
。