gpt4 book ai didi

node.js - Node/Express - 保护客户端/服务器之间通信的好方法

转载 作者:IT老高 更新时间:2023-10-28 13:35:55 25 4
gpt4 key购买 nike

我正在使用 Node/Express 构建一个后端 API,它从 MongoDB 获取数据。前面会用 React 写。

我想保护通信客户端/服务器,但我不知道我必须如何考虑这个过程。

我看到很多关于 passportJWT 的教程,但这对于用户身份验证很有用。

我不知道根据时间(例如)为每个请求创建一个 token 是一种好方法,还是对于网络应用来说太消耗了。

但我的目标是保护数据,因为即使 API 是私有(private)的,您也可以轻松找到路由并尝试找出如何使用 Postman 或其他方式伪造请求以废弃数据。

最佳答案

公认的标准是使用固定的 API KEY。这种信息和平应该是您在 header 中的每个请求中发送的随机生成的字符串。您的服务器必须每次检查 HTTP 请求以查看 API KEY 是否存在于 header 中,如果存在,则必须检查环境变量中存储的值(切勿将 API KEY 存储在代码中)。

如果 API KEY 被泄露,那么您可以轻松地更新 env 变量,然后您又好了。

现在,如果没有 HTTPS 连接,此解决方案将毫无意义,因为任何人都可以嗅探流量并查看 API KEY。在这种情况下,必须使用加密连接。

几乎所有拥有公共(public) API 的公司都使用这种方法:Twitter、Facebook、Twilio、Google 等。

例如,谷歌有一个额外的步骤,他们会给你一个将过期的 token ,但在你的情况下,这将是一个过度杀戮:至少在开始时。

以下代码是我实现 API KEY 检查的示例

app.use(function(req, res, next) {

//
// 1. Check if the APIKey is present
//
if(!req.headers.authorization)
{
return res.status(400).json(
{
message: "Missing APIKey.",
description: "Unable to find the APIKey"
}
);
}

//
// 2. Remove Basic from the beginning of the string
//
let noBasic = req.headers.authorization.replace('Basic ', '');

//
// 3. Convert from base64 to string
//
let b64toString = new Buffer(noBasic, 'base64').toString("utf8");

//
// 4. Remove the colon from the end of the string
//
let userAPIKey = b64toString.replace(':', '');

//
// 5. Check if the APIKey matches the one on the server side.
//
if(userAPIKey != process.env.API_KEY)
{
return res.status(400).json(
{
message: "APIKey don't match",
description: "Make sure what you are sending is what is in your server."
}
);
}

//
// -> Go to the next stage
//
next()

});

您可以使用整个实现检查整个文件hear .

关于node.js - Node/Express - 保护客户端/服务器之间通信的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38844689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com