如何允许特定服务器访问我的 API? [英] How to allow a specific server to access my API?

查看:33
本文介绍了如何允许特定服务器访问我的 API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node.js、express 和 mongodb 编写 API,它将在另一台服务器中使用.我只希望该服务器(或将来更多)能够访问我的 API.我该怎么做?

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?

推荐答案

如果你只想根据对方服务器的 IP 进行限制,那么你可以定义一个 express 中间件来检查每个传入的请求,如果 IP 不是正确的,返回一个错误.

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
});

如果您的 API 位于一个或多个代理(或负载平衡器)之后,您可能应该启用信任代理"选项(http://expressjs.com/guide/behind-proxies.html).

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).

此中间件将根据您的请求,根据传入请求的 IP 地址限制对您的 API 的访问.

This middleware will restrict access to your API based on the IP address of the incoming request, as you requested.

然而,这相当脆弱,因为如果您移动服务器会发生什么?您现在需要更新您的 API 应用程序以接受不同的 IP 地址.

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 的过滤.您可以将 Passport 与 Express 结合使用,为您的 API 添加各种身份验证方案.

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.

最后,无论哪种情况,如果您真的关心 API 的安全性,您可能应该确保您的 API 受到 TLS/SSL 加密保护.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆