简体   繁体   English

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

[英]Intercept/stop ASP.NET Identity unauthorized redirect for authenticated users

ASP.NET Identity issues a 302 Found response, redirecting to the Login page for all unauthorized requests, including authenticated requests with insufficient permissions. ASP.NET Identity发出302 Found响应,将所有未经授权的请求重定向到“登录”页面,包括权限不足的经过身份验证的请求。 It's a confusing user experience to redirect an authenticated user to a login page. 将经过身份验证的用户重定向到登录页面是一种令人困惑的用户体验。

How can I intercept/stop/cancel this redirect for authenticated users and issue a 403 Forbidden response (and therefore show my custom 403 page) instead? 我该如何为经过身份验证的用户拦截/停止/取消此重定向,并发出403禁止响应(并因此显示我的自定义403页面)? Unauthenticated users should continue to see the standard behavior. 未经身份验证的用户应继续看到标准行为。

I've tried adding a simple custom Owin Middleware before and after the CookieAuthenticationMiddleware but could not figure out how to identify an unauthorized request. 我曾尝试在CookieAuthenticationMiddleware之前和之后添加一个简单的自定义Owin中间件,但无法弄清楚如何识别未经授权的请求。

You need to have a custom Authentication Filter with similar code: 您需要具有类似代码的自定义身份验证过滤器:

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);
        }
    }
}

And then instead of [Authorise] you need to apply [MyAuthorise] attribute to your controllers. 然后,需要将[MyAuthorise]属性应用于控制器,而不是[Authorise]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM