向 OPTIONS 请求添加身份验证 [英] Add authentication to OPTIONS request

查看:51
本文介绍了向 OPTIONS 请求添加身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I add headers to the OPTIONS request made towards a cross-domain API?

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

The API I'm working against requires a JWT token set as Authorization header on all requests.

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

When I try to access to the API Angular first performs an OPTIONS request that doesn't care about my headers that I setup for the "real" request like this:

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 请求失败.

When no token is provided, the API returns HTTP status 401 and Angular thinks the OPTIONS request fails.

推荐答案

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

According to the CORS specification when a preflight request is performed user credentials are excluded.

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

(...) using the method OPTIONS, and with the following additional constraints:

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

(重点是我的)

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

With this in mind, the problem seems to be on the API side of things, which should be accepting OPTIONS requests without requiring authentication.

这篇关于向 OPTIONS 请求添加身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆