I need to allow requests from some origins or all requests if they are from a specific user-agent.
...
var whitelist = [URL1, URL2];
corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || origin.req.header['user-agent'] === 'SpecificUserAgent') {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
};
...
Being origin.req.header['user-agent'] === 'SpecificUserAgent' just a sample what I need.
Is there any way to do it? Tanks.
CodePudding user response:
You could write your own middleware on top of all the routes you'd like to protect, and parse user-agents just like you did.
However this method gives no safety at all as a user-agent can be spoofed easily.
app.use((req, res, next) => {
if(!req.headers['user-agent'].match(/firefox/gi))
return res.status(403).send({error: "Unauthorized browser"})
next()
})