AuthorizeAttribute 广告注销 MVC

AuthorizeAttribute adal signout MVC

我已经在 MVC 中创建了一个基于 AAD 组的自定义授权属性。如果我 return false 在属性中应用程序进入登录页面的无限循环。在 MVC 应用程序中使用 adal 时如何从自定义授权属性注销用户?

I think I found a solution I am testing as we speak: 

protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);

        var allowedGroups = GetAllowedGroups();

        var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        string callbackUrl = urlHelper.Action("SignOutCallback", "Account", routeValues: null, protocol: httpContext.Request.Url.Scheme);

        httpContext.GetOwinContext().Authentication.SignOut(
            new AuthenticationProperties { RedirectUri = callbackUrl },
            OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);

        return authorized;
    }

当用户通过身份验证但没有角色(自定义属性中返回false)时,授权属性会将响应更改为401。只有当用户通过身份验证并具有角色时(自定义返回true)属性)授权属性不会更改响应。

如果您正在使用 FormsAuthentication 或 OWIN Cookie 身份验证中间件并且用户已经登录,他将再次被重定向到登录页面,如果您考虑的话,这有点奇怪。 "I've already logged in, and now I'm back do the log in page just because I clicked some link, and no one told me why this just happened."

AuthorizeAttribute 提供了一个名为 HandleUnauthorizedRequest 的受保护虚拟方法,您可以覆盖它,检查用户是否通过身份验证并显示错误页面。例如:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }

您还可以通过覆盖 HandleUnauthorizedRequest 方法在您的自定义 AuthorisationAttribute 中重定向未经授权的用户:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

请阅读here了解更多详情。