【发布时间】:2016-11-25 05:33:15
【问题描述】:
在调试我遇到的 CORS 问题时,我发现了以下行为。 Chrome 发出以下 OPTIONS 预检请求(由 Chrome 自己用 CURL 重写):
curl -v 'https://www.example.com/api/v1/users' -X OPTIONS -H 'Access-Control-Request-Method: POST' -H 'Origin: http://example.com' -H 'Accept-Encoding: gzip,deflate,sdch' -H 'Accept-Language: es-ES,es;q=0.8,en;q=0.6' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36' -H 'Accept: */*' -H 'Referer: http://example.com/users/new' -H 'Connection: keep-alive' -H 'Access-Control-Request-Headers: accept, x-api-key, content-type'
如果满足以下条件,则服务器对此请求的响应:
< HTTP/1.1 403 Forbidden
< Date: Thu, 21 Jul 2016 14:16:56 GMT
* Server Apache/2.4.7 (Ubuntu) is not blacklisted
< Server: Apache/2.4.7 (Ubuntu)
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< Strict-Transport-Security: max-age=31536000 ; includeSubDomains
< X-Frame-Options: SAMEORIGIN
< Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
< Content-Length: 20
< Keep-Alive: timeout=5, max=100
< Connection: Keep-Alive
作为响应“无效 CORS 请求”的主体。如果我重复删除标头“Access-Control-Request-Method”(并且仅该标头)的请求,则 OPTIONS 请求会成功并具有以下响应:
< HTTP/1.1 200 OK
< Date: Thu, 21 Jul 2016 14:21:27 GMT
* Server Apache/2.4.7 (Ubuntu) is not blacklisted
< Server: Apache/2.4.7 (Ubuntu)
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< Strict-Transport-Security: max-age=31536000 ; includeSubDomains
< X-Frame-Options: SAMEORIGIN
< Access-Control-Allow-Headers: origin, content-type, accept, x-requested-with, x-api-key
< Access-Control-Max-Age: 60
< Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
< Access-Control-Allow-Origin: *
< Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
< Content-Length: 0
< Keep-Alive: timeout=5, max=100
< Connection: Keep-Alive
但是,有问题的标头是CORS spec standard header,所以它不应该阻止请求成功,对吧?为什么这个标头会导致这种行为?
当使用 Chrome 发出请求时,如何调整服务器发送的访问控制标头以使请求正常工作?
顺便说一句,我使用的是 Chrome 36.0,服务器使用的是 Spring Boot,CORS 标头由 Spring 管理。
当 Firefox (v47.0) 发出请求时,行为不同,但结果类似。 Firefox 甚至不发送预检请求,它直接发送 POST 请求,该请求收到 403 Forbidden 作为响应。但是,如果我使用“复制为 cURL”选项复制请求,并从终端窗口重复它,它会成功并在响应中发送正确的 CORS 标头。
有什么想法吗?
更新:Firefox 确实发送了预检 OPTIONS 请求(如 Live HTTP 标头插件所示),但 Firebug 将其屏蔽,因此两种浏览器中的行为完全相同。在这两种浏览器中,“Access-control-request-method”标头是导致请求失败的区别。
【问题讨论】: