bman
bman

Reputation: 5235

The "Authorization" header is not sent in OPTIONS call by the browser

I have a very simple HTTP call:

fetch('http://127.0.0.1:5500/v1/homes/', {
  method: "GET", 
  mode: "cors", 
  credentials: "same-origin", 
  headers: {
     Authorization: "TEST"
  }})
  .then(function(response) {
    console.log(response);
  });

But when I look into the "Networks" tab of Google Chrome DevTools, the OPTIONS request does not have the "Authorization" header in it. This causes the server to replies with 401 Unauthorized.

The browser's curl equivalent of the request:

curl 'http://127.0.0.1:5500/v1/homes/' \
-X OPTIONS -H 'Access-Control-Request-Method: GET' \
-H 'Origin: http://localhost:8100'
-H 'Referer: http://localhost:8100/'
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
-H 'Access-Control-Request-Headers: authorization'
--compressed

Am I doing something wrong in the client side or is it quite common that browsers do not send the Authorization header in OPTIONS request, and therefore, I need to change the server in a way to response to OPTIONS call without requiring Authorization header?

Upvotes: 14

Views: 13196

Answers (2)

SubSul
SubSul

Reputation: 2563

An Options call is requested by the client, in your case Chrome browser implicitly before the actual GET call.

From MDN

The HTTP OPTIONS method is used to describe the communication options for the target resource. The client can specify a URL for the OPTIONS method, or an asterisk (*) to refer to the entire server.

On the server side, you'll have to intercept this Options request and respond back with a HTTP Status code of 200 and a Allow header indicating the operations that are permitted on this resource. eg: Allow: HEAD,GET,PUT,DELETE,OPTIONS

The browser on receiving these details will then proceed with the Get call.

Upvotes: 5

Quentin
Quentin

Reputation: 943564

is it quite common that browsers do not send the Authorization header in OPTIONS request

More than common. It is required by the CORS spec which says "for a cross-origin request with preflight … make a preflight request … Exclude user credentials".

I need to change the server in a way to response to OPTIONS call without requiring Authorization header?

Yes

Upvotes: 28

Related Questions