I am writing an API using node.js,express and mongodb, which will be used in another server. I just want only that server (or some more in the future) to be able to access my API. How can I do that?
If you only want to restrict based on the IP of the other server, then you can define an express middleware that checks each incoming request and if the IP is not the correct one, return an error.
An example of that might look like this:
var app = express();
app.use(function (req, res, next) {
if (req.ip !== '1.2.3.4') { // Wrong IP address
res.status(401);
return res.send('Permission denied');
}
next(); // correct IP address, continue middleware chain
});
If your API is behind one or more proxies (or load-balancers), you should probably enable the 'trust proxy' option (http://expressjs.com/guide/behind-proxies.html).
This middleware will restrict access to your API based on the IP address of the incoming request, as you requested.
However, this is rather brittle, because what happens if you move your server? You now need to update your API application to accept a different IP address.
I would strongly encourage you to utilize some form of authentication (pre-shared key) for your API instead of IP-based filtering. You can use Passport with Express to add a variety of authentication schemes for your API.
Finally, in either case, if you really care about the security of your API, you should probably ensure your API is protected with TLS/SSL encryption.
Add a middleware before your handler and validate the req.ip
.
You can use option to initialize the middleware so the IP lists are configurable.
© 2022 - 2024 — McMap. All rights reserved.