向OPTIONS请求添加身份验证

Gle*_*ter 13 api token cors jwt angular

如何OPTIONS在针对跨域API 的请求中添加标头?

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

当我尝试访问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})
            ...
            ...
Run Code Online (Sandbox Code Playgroud)

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

Joã*_*elo 29

根据CORS 规范,当执行预检请求时,将排除用户凭据.

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

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

(重点是我的)

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

  • 目前,在第 3.2.5 节 (https://fetch.spec.whatwg.org/#cors-protocol-and-credentials) 中提到:_“请注意,即便如此,CORS 预检请求也永远不会包含凭据."_ (4认同)