【问题标题】:OnAuthorization Called Twice When Returning Unauthorized Status返回未授权状态时调用两次 OnAuthorization
【发布时间】:2018-07-23 04:31:18
【问题描述】:

我已经实现了自己的AuthorizeAttribute,因为我通过 cookie 传递了我的授权令牌。

public class ValidateToken : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {

            var headers = actionContext.Request.Headers;
            CookieHeaderValue authToken = headers.GetCookies().FirstOrDefault();

            CookieState authCookie = authToken.Cookies.Where(p => p.Name == "AUTH-TOKEN").FirstOrDefault();

            actionContext.Request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authCookie.Value);

            bool isAuth = base.IsAuthorized(actionContext);

            if (!base.IsAuthorized(actionContext)){
                HandleUnauthorizedRequest(actionContext);
            }
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
        }
    }

我的问题是,在HandleUnauthorizedRequest 内部,当我返回HttpStatusCode.Unauthorized 时,再次调用函数OnAuthorization,然后在身份验证检查失败后调用HandleUnauthorizedRequest。在第二次调用中,Web API 返回 401 但是我在前端得到登录屏幕

我不想要。我只想像往常一样返回401。奇怪的是,如果我将HttpStatusCode.Unauthorized 替换为HttpStatusCode.Forbidden,那么该函数不会被第二次调用并立即返回。

编辑我发现OnAuthorization 被调用了两次,并显示了登录表单,因为在 Angular 中我为我的 cookie 传递了withCredentials: true。所以我需要弄清楚为什么withCredentials: true会导致这个。

【问题讨论】:

    标签: c# asp.net asp.net-web-api asp.net-identity authorize-attribute


    【解决方案1】:

    确保匿名身份验证启用并且Windows身份验证禁用

    <IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
    <IISExpressWindowsAuthentication>disabled</IISExpressWindowsAuthentication>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      相关资源
      最近更新 更多