cors
cors copied to clipboard
Add support for having specified domain instead of wildcard
What
We have a use case where we want to allow all domains *
as origin, but we want library to set exact domain value (req.headers.origin) instead of *
in Access-Control-Allow-Origin
header.
The use-case comes as we also need to send credentials such as Cookies to the server. And, with *
as Access-Control-Allow-Origin
, you can't send credentials to the server.
It can be done by adding another option such as exactOriginIfMatches: true
:
var corsOptions = {
origin: '*',
exactOriginIfMatches: true,
}
Current Behaviour*
var corsOptions = {
origin: '*',
};
Request comes from http://example.com -> Library sets `Access-Control-Allow-Origin: *`
Proposed Behaviour*
var corsOptions = {
origin: '*',
exactOriginIfMatches: true,
};
Request comes from http://example.com -> Library sets `Access-Control-Allow-Origin: http://example.com`
var corsOptions = {
origin: '*',
exactOriginIfMatches: false,
};
Request comes from http://example.com -> Library sets `Access-Control-Allow-Origin: *`
In that case, the behaviour will be same but the value of Access-Control-Allow-Origin
will be req.headers.origin
instead of *
. It will be helpful in sending credentials to the server.
Let me know how does it sound? Will be happy to open a PR if that makes sense!
I was digging through MDN docs on CORS, and happened to notice a specific CORS error that suggests an extra-partiuclar reason something like this might be useful:
"Reason: Credential is not supported if the CORS header 'Access-Control-Allow-Origin' is '*" https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
That would make something like this handy.
In the meantime, a second handler after the fact should help workaround this:
app.use(function setSpecificOrigin(req, res, next) {
if (res.get('access-control-allow-origin') === '*') {
res.set('access-control-allow-origin', req.get('origin'))
}
next()
})
Hi, yes, it is a dance with the sec researchers, as they do want things to be secure, but also want cves under their name.
And yes, if the response header of access-control-allow-origin is an asterisk to a preflight request, then a cors based client makes the second, real request it will not include credentials (cookie and authentication headers) with it, even if access-control-allow-credentials is true.
If you want credentials to work from any origin, this module you can set origin: true
to reflect the origin instead of using '*'
https://github.com/expressjs/cors?tab=readme-ov-file#configuration-options