I have cross origin communication enabled on my Node.js server so that my Vue application can access its API from an origin that is different from the origin where static assets are served. This is done using the following code in Node.js:
res.setHeader('Access-Control-Allow-Origin', '*');
along with the following JavaScript code in Vue.:
fetch(url);
This worked fine until I introduced HTTP header based authentication. With that authentication in place, the JavaScript code in Vue was changed from the above to:
fetch(url, {headers: {'Authorization': bearer}});
Once introducing the Authorization header, the browser began to receive the following error when trying to access the API:
Access to fetch at 'https://localhost:8001/articles' from origin http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So, it would seem that introducing the HTTP Authorization header results in preflight requests that fail to pass the preflight test. This notion appears to be substantiated by the Mozilla docs:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
For requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials will result in an error.
So, does this mean that HTTP header based authentication simply can not be implemented in scenario where requests are being made cross origin?
More to the point, how can I implement HTTP header based authorization in my scenario?
check out this package if you are using an express server [1]: https://expressjs.com/en/resources/middleware/cors.html