【问题标题】:node js backend security headernode js后端安全标头
【发布时间】:2022-01-03 22:28:03
【问题描述】:

我正在尝试创建一个登录端点/api,并且我正在通过身份验证标头发送用户登录数据,这对安全性来说可以吗? 授权标头实际上包含一个对象,它被编码为 Base64,它包含用户数据,如散列密码(在此代码中尚未散列)、用户名和某种服务器密钥(如果它是正确的客户端进行授权发送一个 api 请求),只是想确保它是否安全..

const aFunction = (req, res) => {
        require('crypto').randomBytes(48, function(err, buffer) {
            const token = buffer.toString('hex');
            const auth = JSON.parse(Buffer.from(req.headers.authorization, 'base64').toString('ascii')) 
        
            if(auth.serverkey == version["serverkey"]){
                loginUser(auth.username,token).then(data =>{
                
                    if (data.rows.length < 1 || data.rows[0].password != auth.password) {
                        res.send({
                            status: "failed", 
                            message: "Username/Password is wrong", 
                            status_code: 400
                        })
                    }else{
                        res.send({
                            status: "success", 
                            message: "successfully logged in", 
                            status_code: 200, token: token
                        })

                    }

                })
            }else{
                res.send({
                    status: "failed", 
                    message: "Unauthorized Client", 
                    status_code: 401
                })
            }
        });
        
            

        
    }

【问题讨论】:

    标签: javascript node.js express security


    【解决方案1】:

    我会在您的代码中添加对 if (req.secure) 的检查,并拒绝任何来自您的非 https 请求。 (如果您的 nodejs 程序位于反向代理之后,请不要这样做。)

    使用浏览器的用户可以看到您通过 https 或 http 来回发送到服务器的所有内容。 (devtools) 因此,如果通过阅读您的标头,他们可以弄清楚如何向您发送恶意标头,那么有人会的。而且 base64 编码的安全性与完全没有编码完全一样。所以盐和散列你的密码。使用bcrypt package 或 jwts。

    我会以这种方式处理错误,通过使用错误参数调用next() 而不是使用.send() 来传递失败消息。使用这种代码。

    const createError = require('http-errors')
     ...
    const myfunction (req, res, next) {
      ...
      if (!req.secure) return next(createError(403, 'https required'))
      ...
    });
    

    【讨论】:

    • 感谢您的建议,我尝试在我的项目中实现它
    猜你喜欢
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 2018-06-05
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多