节点/ Express-确保客户端/服务器之间安全通信的好方法

Rag*_*nar 5 encryption mongodb node.js express

我正在使用Node / Express构建后端API,该API从MongoDB中获取数据。前端将用React编写。

我想保护通信客户端/服务器的安全,但是我不知道该如何考虑该过程。

我看到了许多有关passport或的教程JWT,但这对用户身份验证很有用。

我不知道基于时间(例如)为每个请求创建令牌是一种好方法还是对于Web应用程序来说太费时了。

但是我的目标是保护数据,因为即使API是私有的,您也可以轻松地找到路由,并尝试弄清楚如何用Postman伪造请求或其他方式来擦除数据。

Dav*_*tti 5

公认的标准是使用固定的API KEY。这种信息安全性应该是您在标头中的每个请求中发送的随机生成的字符串。您的服务器每次必须检查HTTP请求以查看标头中是否存在API KEY,如果存在,则必须对照环境变量中的存储值进行检查(永远不要将API KEY存储在代码中)。

如果API KEY遭到破坏,那么您可以轻松地更新env变量,这又很不错。

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

几乎每个拥有公共API的公司都使用这种方法:Twitter,Facebook,Twilio,Google等。

例如,Google采取了额外的步骤,即给您一个令牌,该令牌将过期,但这在您的情况下是致命的:至少在开始时。

以下代码是我实现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()

});
Run Code Online (Sandbox Code Playgroud)

您可以检查与整个执行整个文件听到