Reputation: 8960
In my MEAN app, i have an API and static web files e.g. index.html
and login.html
.
//Routes
app.use('/mysuperapi', require('./routes/api'));
//For static files
app.use(express.static('site'));
If I didn't want users to be able to go URLs such as mysite.com/mysuperapi
freely - i'm wondering is this is possible if at all?
Pages such login.html
that call an authenticate route in the API would happen from the user's machine, so I can't exactly whitelist all IPs expect my servers.
Or are all APIs simply public?
Any advice appreciated.
Thanks.
Upvotes: 3
Views: 5193
Reputation: 1930
You can restrict access to routes by adding another middleware layer, for instance
app.use('/mysuperapi/*', function(req, res, next) {
// do your filtering here, call a `res` method if you want to stop progress or call `next` to proceed
var ip = req.ip ||
req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
// Your allowed ip. You can also check against an array
if (ip == '5.4.3.2') {
next();
} else {
res.end();
}
}
app.use('/mysuperapi', require('./routes/api'));
// ... the rest of your code
the function on the first app.use statement will be called for every path that matches the pattern and before it reaches your API, so you can restrict access there.
Upvotes: 10