在实际调用我的 passwordMatch 函数之前,Passport 无法使用 "Wrong password" 进行身份验证

Passport fails authentication with "Wrong password" before actually calling my passwordMatch function

这很奇怪。

我想做什么

使用 Passportjs 本地策略和 JWT 在 node.js 中创建身份验证服务器。允许使用电子邮件和密码注册帐户,密码使用 'crypto'

散列

发生了什么事

因此,当我使用正确的密码登录到预先存在的模型时,APi 中的身份验证因密码错误而失败。尽管发生了一些奇怪的事情。

我试过的

基本上当我发出 post 请求时:

我的护照配置中的功能:

if (!profileController.passMatch(username, password)) {
            console.log('pass was wrong');
            return done(null, false, {
                message: 'Password is wrong'
            });
        }

配置文件控制器中的 passMatch 函数:

module.exports.passMatch = (email, password) => {
    User.findOne({email: email}, (err, user) => {
        if (err) { console.log ("error at passMatch: " + err); }
        var hash = crypto.pbkdf2Sync(password, user.salt, 1000, 64, 'sha512').toString('hex');
        console.log(user.hash == hash);
        return (user.hash == hash);
    });
    return false;
};

登录函数:

module.exports.login = (req, res) => {

    console.log('beginning to authenticate');

    passport.authenticate('local', (err, user, info) => {

        console.log ("authenticating");
        var token;

        // If passport throws an error
        if (err) {
            res.status(404).json(err);
            console.log("error logging in");
            return;
        }

        // If a user is found
        if (user) {

            // Respond with JWT
            token = createJwt(user)
            res.status(200);
            res.json({
                "token": token
            })
            console.log("user logged in");

        // If a user wasn't found
        } else {

            res.status(401).json(info);
            console.log(info);
        }

    })(req, res);

};

这是怎么回事?

在 "passMatch" 函数中,我再次查询用户(效率很低),但由于此操作是异步的,因此它被跳过到 "return false" 语句之后和中护照身份验证配置过程,它收到该错误,导致身份验证失败,但 "log" 之后返回,因为它花费了更长的时间。

我是如何修复的

我将passport已经查询到的用户对象而不是用户名传入passMatch,然后有两次操作检查哈希值是否相同并返回,现在可以了。

新码

module.exports.passMatch = (user, password) => {
    var hash = crypto.pbkdf2Sync(password, user.salt, 1000, 64, 'sha512').toString('hex');
    return user.hash == hash;
};

还需要对护照配置进行必要的更改,以将用户而不是用户名作为第一个参数传递给该函数。