ASP.NET标识发出302找到的响应,将所有未经授权的请求重定向到登录页面,包括权限不足的身份验证请求。将经过身份验证的用户重定向到登录页面是一种令人困惑的用户体验。
如何拦截/停止/取消通过身份验证的用户的重定向,并发出403禁止的响应(从而显示自定义的403页)?未经身份验证的用户应继续查看标准行为。
我尝试在CookieAuthenticationMiddleware之前和之后添加一个简单的自定义Owin中间件,但无法确定如何识别未经授权的请求。
发布于 2015-07-09 22:17:58
您需要具有类似代码的自定义身份验证筛选器:
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);
}
}
}然后,您需要将[Authorise]属性应用于控制器,而不是[MyAuthorise]属性。
https://stackoverflow.com/questions/31325811
复制相似问题