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

标签 node.js mongodb express encryption

我正在使用 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/

相关文章:

javascript - expressjs : get requested url

json - 使用 Node 搜索从 API 查询返回的 JSON 中的项目

node.js - 在 Node 和 React 之间共享常量变量

javascript - 如何在 mongoose node.js 中找到数字范围

c#: 元素 'Id' 不匹配任何字段或属性 MongoDB

javascript - $injector :modulerr AngularJS, 到目前为止尝试了一切

javascript - 显式结束响应时调用 express.js 下一个中间件层

node.js - 保护 Express 免受 XSS 攻击 : is it sufficient to encode HTML entities of whole incoming request?

mongodb - Mongoose - 从 DBref 数组和项目本身中删除项目

mongodb - 如何在第二个$match中使用当前字段?