简体   繁体   English

验证NodeJS中的哈希密码

[英]Verify hashed password in NodeJS

I've started learning NodeJS since a few weeks. 从几周开始,我开始学习NodeJS。 I'm building my first application where users can register a account and login with their credentials. 我正在构建我的第一个应用程序,用户可以在其中注册帐户并使用其凭据登录。 When a user registers a account the password will be hashed. 当用户注册帐户时,密码将被散列。 I'm using password-hash from NPM. 我正在使用NPM的密码哈希。 The hashing of the password works fine. 密码的哈希工作正常。 The problem is verifying the password when a user logs in. This is my code: 问题是用户登录时验证密码。这是我的代码:

Registration: 注册:

router.post('/register', function(req, res, next) {
    req.getConnection(function (err, connection) {
        var data = {
            username: req.body.username,
            password: passwordHash.generate(req.body.password),
            mail: req.body.mail,
            hometown: req.body.hometown
        };
        connection.query("INSERT INTO users set ? ", [data], function(err, results) {
            res.redirect('/secret/login');
        });
    });
});

Logging in and verifying hashed password: 登录并验证哈希密码:

router.post('/login', function(req, res, next) {

   var user_login = req.body.username;
   var password_login = req.body.password;

    req.getConnection(function(err, connection) {

        if (err) throw err;

        connection.query('SELECT * FROM users WHERE username = ?', [user_login], function(err, results) {

            if(results[0] && passwordHash.verify(password_login, results[0].password)) {

                  req.session.regenerate(function(){
                  req.session.login = true;
                  req.session.username = user_login;
                  req.session.data = results[0];
                  res.redirect(req.baseUrl);

            });

            } else {

                console.log(results[0]); // true
                res.redirect(req.baseUrl);

            }

        });

      });

    });

I've also tried 我也尝试过

console.log(passwordHash.verify(password_login, results[0].password));

When I sign in with the username & password from one of the registred accounts, the boolean response in the console.log is 'false' every time. 当我使用其中一个注册帐户的用户名和密码登录时,console.log中的布尔响应每次都为“ false”。 I couldn't find a answer on the internet so thats why I'm asking it here. 我在互联网上找不到答案,所以这就是为什么我在这里问。 I hope someone can help me solve this! 我希望有人可以帮助我解决这个问题!

I'm using these modules: 我正在使用以下模块:

"ejs": "^2.3.4",
"express": "^4.13.3",
"express-myconnection": "^1.0.4",
"multer": "^1.1.0",
"mysql": "^2.9.0",
"password-hash": "^1.2.2"

What am I doing wrong when verifying the hashed password? 验证哈希密码时,我在做什么错?

I've found the problem .. The password was saved in my database as a varchar(50) .. Had to be varchar(88). 我发现了问题..密码以varchar(50)的形式保存在数据库中。.必须是varchar(88)。 Thanks for reading and answering! 感谢您的阅读和回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM