Reputation: 10818
I am using this module to handle cors requests https://www.npmjs.com/package/cors I need to restrict all domains except whitelisted
From official CORS module example:
var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.get('/products/:id', cors(corsOptions), function(req, res, next){
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
});
Which I have changed to this to make it work:
var origin;
var corsOptions;
app.all('*', function (req, res, next) {
origin = req.get('origin');
var whitelist = ['http://example1.com', 'http://example2.com'];
corsOptions = {
origin: function (origin, callback) {
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
next();
});
app.post('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });
});
Then I run test from http://localhost:8080
by posting to app.post('/products/:id'...)
I expected it should not be executed because http://localhost:8080
is not whitelisted but actually it did. Any idea why and how to fix that?
Also I didadd cors(corsOptions)
to watch but it is saying - not available
Upvotes: 1
Views: 16401
Reputation: 559
Here is my solution in nodejs expressjs
.
.env
file. so that no one knows which domains you whitelisted.ALLOWED_ORIGINS=https://foo.example1 https://foo.example2
customCorsOptions
.const customCorsOptions = {
origin: (origin, callback) => {
const allowedOrigins = process.env.ALLOWED_ORIGINS.split(" ");
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error("Request from unauthorized origin"));
}
},
};
export default customCorsOptions;
cors
.import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import customCorsOptions from "./middleware/customCorsOptions.js";
/* CONFIGURATION */
dotenv.config(); // This needs to be configured first to use env variables everywhere
const app = express();
app.use(cors(customCorsOptions));
// other codes in your server.js
Upvotes: 2
Reputation: 106698
The reason is that corsOptions
is still undefined
when cors(corsOptions)
is called (effectively the same as cors()
) since cors(corsOptions)
is evaluated immediately during startup.
Upvotes: 3