'When calling my API from the same site, I cannot have CORS activated, because the Origin header will be missing
I'm struggling with CORS. I have a web app that calls my API. In development, let's say the API is at site.com:3000/api and the site at site.com. In production, the API is at site.com/api and the site on site.com (which is considered "same-site").
So, my problem is that I cannot enforce CORS properly, because my API is on the same site as my web app, because the "Origin" request header will be non-existent in this case. Which means, my code can't verify it, and denies the request. And I cannot disregard the missing Origin in this case, because that would invalidate the whole CORS implementation.
I still want to have CORS, but also run APIs and site on the same origin/site. What am I missing?
I'm implementing a whitelist with cors in a nodejs app, with express and all that.
const whitelist = config.cors_origin_list.split(",");
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
Then
app.use('/api/aroute', cors(corsOptions), aroute);
Edit: Why are people voting negatively on this? Have I done something wrong?
Solution 1:[1]
The first rule about CORS is that, in the absence of the Origin header, everything is allowed. CORS only deals with "cross-origin" requests, that is, requests in which the Origin header is set.
When implementing CORS, a server must never raise an error. Its only duty is to set (or not set) the Access-Control-* headers in the response, and the browser must decide whether to raise an error. For example, if the browser made the request without Origin header, it will process the response regardless of any Access-Control-* headers.
With the following code, a response from your production site will lack the headers, but the browser will not complain about that.
if (whitelist.indexOf(origin) !== -1) {
callback(null, true); // set Access-Control-* headers
} else {
callback(null, false); // don't set Access-Control-* headers
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
