Reputation: 128
I have a Node.js backend using express that only allows requests coming from a specific origin (let's call it localhost:8998
). I'd like to create a public API for the backend, however, authorized with a token rather than by the origin.
Is it even possible to create these kind of routes?
I was thinking of going about this by setting the Access-Control-Allow-Origin
header to whatever the request's origin when the request's route is one of the public API routes. Something like this:
app.use(function(req, res, next) {
var origin = req.get('origin');
res.header("Access-Control-Allow-Origin", origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Seems like I'm going against the original intentions of the Access-Control-Allow-Origin
header. Wanted to hear your guys' thoughts on this/how I should go about implementing a public API.
Upvotes: 1
Views: 3934
Reputation: 19372
Make middlewares:
const allowCORS = function(req, res, next) {
var origin = req.get('origin');
res.header("Access-Control-Allow-Origin", origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
};
const allowAllIfAuthorized = function(req, res, next) {
if (req.isAuthorized) {
return allowAll(req, res, next);
}
next();
};
const allowedTokens = [...];
const isAuthorized = function(req, res, next) {
req.isAuthorized = (
req.query.accessToken
&& allowedTokens.includes(req.query.accessToken)
);
next();
}
and attach in certain routes:
app.get('/', (req, res) => res.render('index'));
app.use(
'/api',
allowCORS, // allow cors for public api
require('./api'));
app.use(
'/private/api',
isAuthorized, allowCORSIfAuthorized, // allow cors if user authorized
require('./private/api'));
I'd like to create a public API for the backend, however, authorized with a token rather than by the origin.
so it's should be cors all rule everywhere, You're preventing from private access using access tokens which authorized users will have.
Summary: CORS is not firewall (gatekeeper) from unauthorized users
Upvotes: 3