Bcrypt-NodeJS compare() returns false 无论密码是什么

Bcrypt-NodeJS compare() returns false whatever the password

我知道这个问题已经被问过几次了(比如 here, here or , or even on Github,但是 none 的答案实际上对我有用...

我正在尝试使用 Mongoose 和 Passport 为 NodeJS 应用程序开发身份验证,并使用 Bcrypt-NodeJS 来散列用户密码。

在我决定重构用户模式并使用 bcrypt 的异步方法之前,一切都没有任何问题。创建新用户时哈希仍然有效,但我现在无法根据存储在 MongoDB.

中的哈希验证密码

我知道什么?

  1. bcrypt.compare()总是returnsfalse无论密码是否正确,无论密码是什么(我尝试了几个字符串)。
  2. 密码仅在用户创建时被散列一次(因此不会重新散列)。
  3. 提供给比较方法的密码和散列是正确的,顺序正确。
  4. 密码和哈希的类型为"String"。
  5. 哈希存储在数据库中时不会被截断(60 个字符长的字符串)。
  6. 数据库中获取的哈希值与用户创建时存储的哈希值相同。

代码

用户架构

一些字段已被删除以保持清晰,但我保留了相关部分。

var userSchema = mongoose.Schema({

    // Local authentication
    password: {
        hash: {
            type: String,
            select: false
        },
        modified: {
            type: Date,
            default: Date.now
        }
    },

    // User data
    profile: {
        email: {
            type: String,
            required: true,
            unique: true
        }
    },

    // Dates
    lastSignedIn: {
        type: Date,
        default: Date.now
    }
});

密码散列

userSchema.statics.hashPassword = function(password, callback) {
    bcrypt.hash(password, bcrypt.genSaltSync(12), null, function(err, hash) {
        if (err) return callback(err);
        callback(null, hash);
    });
}

密码比较

userSchema.methods.comparePassword = function(password, callback) {
    // Here, `password` is the string entered in the login form
    // and `this.password.hash` is the hash stored in the database
    // No problem so far
    bcrypt.compare(password, this.password.hash, function(err, match) {
        // Here, `err == null` and `match == false` whatever the password
        if (err) return callback(err);
        callback(null, match);
    });
}

用户认证

userSchema.statics.authenticate = function(email, password, callback) {
    this.findOne({ 'profile.email': email })
        .select('+password.hash')
        .exec(function(err, user) {
            if (err) return callback(err);
            if (!user) return callback(null, false);

            user.comparePassword(password, function(err, match) {
                // Here, `err == null` and `match == false`
                if (err) return callback(err);
                if (!match) return callback(null, false);

                // Update the user
                user.lastSignedIn = Date.now();
                user.save(function(err) {
                    if (err) return callback(err);
                    user.password.hash = undefined;
                    callback(null, user);
                });
            });
        });
}

这可能是我犯的一个 "simple" 错误,但我在几个小时内没有发现任何错误......如果你有任何想法使该方法有效,我很乐意阅读它。

谢谢大家

编辑:

当运行这段代码时,match实际上等于true。所以我知道我的方法是正确的。我怀疑这与哈希在数据库中的存储有关,但我真的不知道是什么导致了这个错误的发生。

var pwd = 'TestingPwd01!';
mongoose.model('User').hashPassword(pwd, function(err, hash) {
    console.log('Password: ' + pwd);
    console.log('Hash: ' + hash);
    user.password.hash = hash;
    user.comparePassword(pwd, function(err, match) {
        console.log('Match: ' + match);
    });
});

编辑 2(和解决方案):

我把它放在那里以防有一天它对某人有帮助...

我在我的代码中发现了错误,这是在用户注册期间发生的(实际上是我在此处没有 post 的唯一代码)。我正在散列 user.password 对象而不是 user.password.plaintext...

只有将我的依赖项从 "brcypt-nodejs" 更改为 "bcryptjs" 我才能找到错误,因为 bcryptjs 在被要求散列对象时抛出错误,而 brcypt-nodejs 只是散列对象就好像它是一个字符串。

bcrypt.hash() 有 3 个参数...出于某种原因你有 4 个。

而不是

bcrypt.hash(password, bcrypt.genSaltSync(12), null, function(err, hash) {

应该是

bcrypt.hash(password, bcrypt.genSaltSync(12), function(err, hash) {

由于您仅在创建用户期间进行哈希处理,因此您可能没有正确进行哈希处理。您可能需要重新创建用户。

我知道已经找到了解决方案,但以防万一您从 google 搜索中登陆这里并遇到同样的问题,特别是如果您使用的是 schema.pre("save") 功能,有时会有多次保存同一个模型的倾向,因此每次 重新散列 密码。如果您在 mongoDB 中使用引用来创建架构关系,则尤其如此。这是我的注册函数的样子:

注册码

User.create(newUser, (err, user) => {
            if (err || !user) {
                console.warn("Error at stage 1");
                return res.json(transformedApiRes(err, "Signup error", false)).status(400);
            }
            let personData: PersonInterface = <PersonInterface>{};
            personData.firstName = req.body.first_name;
            personData.lastName = req.body.last_name;
            personData.user = user._id;
            Person.create(personData, function (err1: Error, person: any): any {
                if (err1 || !person) {
                    return res.json(transformedApiRes(err1, "Error while saving to Persons", false));
                }
                /* One-to-One relationship */
                user.person = person;
                user.save(function (err, user) {
                    if (err || !user) {
                        return res.json({error: err}, "Error while linking user and person models", false);
                    }
                    emitter.emit("userRegistered", user);
                    return res.json(transformedApiRes(user, `Signup Successful`, true));
                });
            });
        });

如您所见,User 上有一个嵌套保存,因为我必须 link User 模型与 Person 模型(一对一)。结果,我遇到了不匹配错误,因为我使用的是预保存函数,每次触发 User.create 或 User.save 时,都会调用该函数并重新散列现有密码。 pre-save 中的控制台语句给了我以下内容,表明该密码确实已重新哈希处理:

单次注册调用后的控制台调试

{ plain: 'passwd',
  hash: 'b$S2g9jIcmjGxE0aT1ASd6lujHqT87kijqXTss1XtUHJCIkAlk0Vi0S' }
{ plain: 'b$S2g9jIcmjGxE0aT1ASd6lujHqT87kijqXTss1XtUHJCIkAlk0Vi0S',
  hash: 'b$KRkVY3M8a8KX9FcZRX.l8.oTSupI/Fg0xij9lezgOxN8Lld7RCHXm' }

修复,解决方案

要解决此问题,您必须修改您的预 ("save") 代码以确保密码仅在第一次保存到数据库或已被修改时才进行哈希处理。为此,请将您的预保存代码包围在这些块中:

if (user.isModified("password") || user.isNew) {
    //Perform password hashing here
} else {
    return next();
}

这是我的整个预保存功能的样子

UsersSchema.pre("save", function (next: NextFunction): any {
    let user: any = this;
    if (user.isModified("password") || user.isNew) {
        bcrypt.genSalt(10, function (err: Error, salt: string): any {
            if (err) {
                return next(err);
            }
            bcrypt.hash(user.password, salt, function (err: Error, hash: string) {
                if (err) {
                    console.log(err);
                    return next(err);
                }
                console.warn({plain: user.password, hash: hash});
                user.password = hash;
                next();
            });
        });
    } else {
        return next();
    }
});

希望这对某人有所帮助。

我把它放在这里是因为它有一天可能会对某人有所帮助。

在我自己的案例中,即使我提供了正确的身份验证详细信息,我仍然有 bcrypt.compare as false 的原因是模型中数据类型的限制。因此,每次将哈希值保存在数据库中时,都会将其截断以适应 50 个字符限制。

我有

    'password': {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: "null"
    },

字符串只能包含50 characters,但bcrypt.hash的结果不止于此。

修复

我修改了模型 DataTypes.STRING(255)

提示:如果你正在切换

then().then()

阻止总是检查 return 值。

您可以随时检查数据库中密码字段的最大长度。确保它很大。就我而言,我已将其设置为 500。然后代码完美运行!

TS 版本

const { phone, password } = loginDto;
            const user = await this.usersService.findUserByPhone(phone);
            const match = await compare(password, user.password);
            if (user && match){
                return user
            }else{
                throw new UnauthorizedException();
            } 

JS版本

const { phone, password } = loginDto;
                const user = await this.usersService.findUserByPhone(phone);
                const match = await bcrypt.compare(password, user.password);
                if (user && match){
                    return user
                }else{
                    throw new UnauthorizedException();
                }