【问题标题】:Add authentication to OPTIONS request向 OPTIONS 请求添加身份验证
【发布时间】:2017-04-04 23:56:18
【问题描述】:

如何向跨域 API 发出的 OPTIONS 请求添加标头?

我正在使用的 API 需要在所有请求中将 JWT 令牌设置为 Authorization 标头。

当我尝试访问 API 时,Angular 首先执行一个 OPTIONS 请求,该请求不关心我为“真实”请求设置的标头,如下所示:

this._headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer my-token-here'
});

return this._http
            .post(AppConfig.apiUrl + 'auth/logout', params, {headers: this._headers})
            ...
            ...

当没有提供令牌时,API 返回 HTTP 状态 401,Angular 认为 OPTIONS 请求失败。

【问题讨论】:

    标签: api angular cors token jwt


    【解决方案1】:

    可以使用withCredentials 选项为 CORS 预检请求提供身份验证:

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      constructor() {
      }
    
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        request = request.clone({
          withCredentials: true
        });
        return next.handle(request);
      }
    }
    

    另见:

    https://stackoverflow.com/a/38615675/166850

    【讨论】:

      【解决方案2】:

      根据 CORS specification when a preflight request 执行,用户凭据被排除在外。

      (...) 使用方法 OPTIONS,并具有以下附加约束:

      • (...)
      • 排除作者请求标头。
      • 排除用户凭据。
      • (...)

      (重点是我的)

      考虑到这一点,问题似乎出在 API 方面,应该接受OPTIONS 请求而不需要身份验证

      【讨论】:

      • 出处是生活水准,不再有引文。这个答案在 2021 年仍然正确吗?
      • 目前,在第 3.2.5 节 (fetch.spec.whatwg.org/#cors-protocol-and-credentials) 中提到:“请注意,即便如此,CORS 预检请求永远不会包含凭据。”
      • 谢谢。我正在搜索“用户凭据”并且非常困惑。显然,我也不擅长阅读英语。
      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多