[英]How to allow a specific server to access my API?
I am writing an API using node.js,express and mongodb, which will be used in another server. 我正在使用node.js,express和mongodb编写API,它将在另一台服务器中使用。 I just want only that server (or some more in the future) to be able to access my API. 我只想要那个服务器(或将来的某个服务器)能够访问我的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. 如果您只想基于其他服务器的IP进行限制,那么您可以定义一个快速中间件来检查每个传入请求,如果IP不正确,则返回错误。
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 ). 如果您的API位于一个或多个代理(或负载均衡器)后面,则应该启用“信任代理”选项( 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. 根据您的请求,此中间件将根据传入请求的IP地址限制对API的访问。
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. 您现在需要更新API应用程序以接受其他IP地址。
I would strongly encourage you to utilize some form of authentication (pre-shared key) for your API instead of IP-based filtering. 我强烈建议您为API而不是基于IP的过滤使用某种形式的身份验证(预共享密钥)。 You can use Passport with Express to add a variety of authentication schemes for your API. 您可以使用Passport with Express为您的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. 最后,在任何一种情况下,如果您真的关心API的安全性,您应该确保您的API受TLS / SSL加密保护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.