【问题标题】:Angular CORS simple request triggers preflight with Authorization header in POSTAngular CORS 简单请求在 POST 中触发带有 Authorization 标头的预检
【发布时间】:2017-11-04 17:06:17
【问题描述】:

根据文档:https://developer.mozilla.org/en/docs/Web/HTTP/Access_control_CORS),对于简单请求不应进行预检。

如果我不在请求中添加额外的“授权”标头,情况确实如此:

"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic _base64_string_"

没有“授权”标头:

:authority:www.target.com
:method:POST //<----------------This is correct
:path:/oauth2/access_token?client_id=xxx-xxx
:scheme:https
accept:application/json, text/plain, */*
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.8,fr;q=0.6
content-length:79
content-type:application/x-www-form-urlencoded//<----------------This is correct
origin:http://source.com:4200
referer:http://source.com:4200/

带有“Authorization”标头,自动设置OPTIONS方法:

:authority:www.target.com
:method:OPTIONS //<----------------This is NOT correct, caused by Authorization header
:path:/oauth2/access_token?client_id=xxx-xxx
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, sdch, br
accept-language:en-US,en;q=0.8,fr;q=0.6
access-control-request-headers:authorization
access-control-request-method:POST
origin:http://source.com:4200
referer:http://source.com:4200/

由于这个问题,我无法授权我的应用,服务器响应是:

HTTP method 'OPTIONS' is not allowed. Expected 'POST'

因此,“授权”标头似乎触发了 CORS 中的预检。 任何人都可以对此有所了解吗?

【问题讨论】:

    标签: angular cors authorization preflight


    【解决方案1】:

    由于这个问题,我无法授权我的应用,服务器响应是:

    HTTP method 'OPTIONS' is not allowed. Expected 'POST'
    

    如果您对发送请求的服务器具有管理员访问权限,则需要将该服务器配置为允许 HTTP OPTIONS 请求,并使用 Access-Control-Allow-HeadersAccess-Control-Allow-Methods 响应标头响应它们浏览器需要查看以允许实际的 GETPOST 或您尝试进行的任何操作(除了 Access-Control-Allow-Origin 响应标头,浏览器需要查看实际请求)。

    如果您没有对该服务器的管理员访问权限,无法将其配置为向 OPTIONS 请求发送支持 CORS 的响应,那么从前端 JavaScript 代码获取请求以使用它的唯一选择是设置一个CORS 代理并通过它发出请求。 "No 'Access-Control-Allow-Origin' header is present on the requested resource" 的答案有详细的操作方法。

    除此之外,您唯一的其他选择是不从您的前端 JavaScript 代码发出请求,而是从您自己的后端代码发出请求,这绕过了浏览器施加的跨域限制)。

    因此,“授权”标头似乎触发了 CORS 中的预检。有人能解释一下吗?

    是的,当您添加 Authorization 标头时,它不再是“简单请求”。

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests 解释了这一点;它说触发浏览器进行预检的条件之一是:

    如果,除了用户代理自动设置的标题(对于 例如,ConnectionUser-Agentany of the other header with a name defined in the Fetch spec as a “forbidden header name”), 请求包含除those which the Fetch spec defines as being a “CORS-safelisted request-header” 以外的任何标头,其中 如下:

    Accept
    Accept-Language
    Content-Language
    Content-Type
    DPR
    Downlink
    Save-Data
    Viewport-Width
    Width
    

    Authorization 不在该列表中,因此它会触发预检。

    【讨论】:

    • 我希望能够以某种方式避免仅针对该初始请求使用后端服务器或代理。所有后续请求都在通过,只有这个导致问题(不,我无权访问服务器,它只是 API 访问)。还是谢谢你!
    猜你喜欢
    • 2016-12-28
    • 2012-11-08
    • 2015-04-24
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多