Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS, prevent preflight of request with Authorization header

AngularJS transforms my POST request into OPTIONS when I add Authorization header:

  $http({
    url: ApiEndpoint + 'logout',
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': UserService.getApiKey()
    }
  })

I'm developpling a hybrid mobile application with Ionic that I test in browser, os it's a CORS request.

I have already seen this question. The proposed workaround is to change Content-Type that I did and it worked without Authorization. With Authorization header the request is changed again to OPTIONS method.

Can you propose client solution please because a have no control over server API.

Thank you.

like image 857
VladRia Avatar asked Aug 21 '16 17:08

VladRia


2 Answers

as Developer remarked, the CORS request will be preflighted unless it is a simple request.

like image 99
VladRia Avatar answered Sep 20 '22 02:09

VladRia


As others have noted, what you are seeing are CORS preflight requests.

You can't avoid them if you want to set Authorization header, but there are some workarounds if you control the backend (or are willing to use proxy). More info: https://damon.ghost.io/killing-cors-preflight-requests-on-a-react-spa/

In short:

  • CORS preflight headers can be cached by browser (set Access-Control-Max-Age header to number of seconds the response should be cached)
  • authorization header can be moved to URL params (if this is a good idea or not is a whole other discussion)
  • you can send JSON without proper headers (again, not the best of ideas, but...)
  • if it fits your use case, the simplest solution is to use proxy and thus avoid cross-origin requests completely
like image 26
johndodo Avatar answered Sep 17 '22 02:09

johndodo