I am attempting to update the CORS origins while the NodeJS server is running. I am simply trying to overwrite the previous CORS configuration when a user makes a specific update.
I tried using app.use(setCors(app.get('newCorsDomains')));
.
let setCors = (domains) => {
return cors({
origin: domains
});
};
I have confirmed I am sending the correct domains to this function, but the CORS origins do not seem to be getting updated when app.use(setCors(app.get('newCorsDomains')));
is called.
CodePudding user response:
I don't know why you would want to do this, but if you really do, probably your best bet would be to make a middleware function that wraps the cors middleware. It could look like this.
app.use((req, res, next) => {
cors({ origin: app.get('newCorsDomains') })(req, res, next);
});
CodePudding user response:
TL;DR
It is possible but inadvisable.
More details
Because Express's CORS middleware performs little to no defensive copying, you can actually create a route that modifies the CORS configuration options. Here is a proof of concept:
const express = require('express')
const cors = require('cors')
const app = express()
const port = 3000
const corsOptions = {
origin: 'http://example.com'
}
app.get('/', cors(corsOptions), (req, res) => {
res.send('Hello World!')
})
app.post('/change-allowed-origin', function (req, res, next) {
corsOptions.origin = 'http://attacker.com';
res.send('Done!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
After starting the server locally:
$ curl -s -D - -o /dev/null -H "Origin: https://attacker.com" localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://example.com
Vary: Origin
-snip-
$ curl -XPOST localhost:3000/change-allowed-origin
Done!
$ curl -s -D - -o /dev/null -H "Origin: https://attacker.com" localhost:3000
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://attacker.com
Vary: Origin
-snip-
However, I consider this a misfeature of Express's CORS middleware and I would discourage you from updating your CORS configuration on the fly. Because CORS deactivates security, any change to CORS configuration should instead be carefully reviewed and require a redeployment.