How can I identify a CORS preflight request?

半城伤御伤魂 提交于 2019-12-20 03:01:09

问题


A CORS preflight request obviously uses the OPTIONS method and has an Origin header. However, a browser can decide for any HTTP request to add an Origin header. Also, OPTIONS may be used for other functionality than CORS. (How) Can I identify exactly (without false positives or negatives) whether a request is a CORS preflight request?


回答1:


Check for the Access-Control-Request-Method header. It would not make much sense to send it in a request other than the preflight request.




回答2:


Check for the existence of these essential information present in a preflight request:

  1. The request's HTTP method is OPTIONS
  2. It has an Origin header
  3. It has an Access-Control-Request-Method header, indicating what's the actual method it's trying to use to consume your service/resource

Considerations

In theory you you could be a so clever and manually set those headers and try to make some fake-Preflight request for some reason.

However, your browser would complain with the following sample message: Refused to set unsafe header "Origin" (tested as an XHR request on Chrome) while other apps, such as Postman will set their own Origin as, say Origin: chrome://extension...



来源:https://stackoverflow.com/questions/32331737/how-can-i-identify-a-cors-preflight-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!