拦截/停止经过身份验证的用户的ASP.NET身份未经授权的重定向

时间:2015-07-09 18:47:17

标签: c# asp.net asp.net-identity owin

ASP.NET Identity发出 302 Found 响应,重定向到Login页面以查找所有未经授权的请求,包括权限不足的经过身份验证的请求。将经过身份验证的用户重定向到登录页面是一种令人困惑的用户体验。

如何拦截/停止/取消经过身份验证的用户的此重定向,并发出 403 Forbidden 响应(因此显示我的自定义403页面)?未经身份验证的用户应继续看到标准行为。

我尝试在CookieAuthenticationMiddleware之前和之后添加一个简单的自定义Owin中间件,但无法弄清楚如何识别未经授权的请求。

1 个答案:

答案 0 :(得分:0)

您需要具有类似代码的自定义身份验证过滤器:

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]