Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Max-Age not working with Authorization header

Trying to workout why chrome is still firing prefetch request even though the Access-Control-Max-Age has been specified when combined with the Authorization header. If I remove the Authorization header preflight caching works as expected.

Request headers

:method: OPTIONS
:path: /v1/api
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-GB,en-US;q=0.9,en;q=0.8,pt-BR;q=0.7,pt;q=0.6,fr;q=0.5
access-control-request-headers: authorization,content-type
access-control-request-method: POST
origin: https://null.jsbin.com
referer: https://null.jsbin.com/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site

Response headers

access-control-allow-credentials: true
access-control-allow-headers: *
access-control-allow-methods: OPTIONS,POST
access-control-allow-origin: *
access-control-max-age: 86400
content-length: 0
content-type: application/json
date: Wed, 04 Aug 2021 08:30:50 GMT

I'm slowly grinding through this doc https://fetch.spec.whatwg.org/#http-cors-protocol but can't see any reason why Authorization should block preflight caching.

Also, as an aside. If Authorization is incompatible with Access-Control-Max-Age is it such a bad idea to include the auth token in the body rather than as a header from a security point of view? You may assume, over TLS.

  • Server code: https://glitch.com/edit/#!/prairie-bright-earl?path=server.js%3A22%3A0
  • Client code: https://jsbin.com/dejetem/16/edit?js,console
like image 434
david_adler Avatar asked Sep 05 '25 16:09

david_adler


1 Answers

For reasons that are not totally clear to me, specifying Access-Control-Allow-Headers: Authorization, * "fixes" things and the Access-Control-Max-Age: 10 is respected. The authorization header is an edge case which must be explicitly safe listed by the server [0][1][2]

const buildHeaders = origin => {
  return {
    "Access-Control-Allow-Methods": "*",
    // the key line 👇
    "Access-Control-Allow-Headers": "Authorization, *", 
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Max-Age": "10"
  };
};

fastify.options("/", function(request, reply) {
  reply
    .code(200)
    .headers(buildHeaders(request.headers.origin))
    .send();
});

fastify.post("/", function(request, reply) {
  reply
    .code(200)
    .headers(buildHeaders(request.headers.origin))
    .header("Content-Type", "application/json; charset=utf-8")
    .send({ hello: "world" });
});

const url = 'https://dynamic-past-deltadromeus.glitch.me/'
const opts = {
    headers: {
        'Content-Type': 'application/json', 
        'Authorization': 'asdf'
    },
    method: 'POST',
    body: JSON.stringify({ message: 'ping' }),
}
fetch(url,opts)

Source code:

  • Server source code https://glitch.com/edit/#!/dynamic-past-deltadromeus?path=server.js%3A8%3A0
like image 134
david_adler Avatar answered Sep 07 '25 16:09

david_adler