为什么在使用 argon2 验证密码哈希的 NestJS 中 isPasswordValid 总是 false?

问题描述 投票:0回答:0

我正在做一个 NestJS 项目,我使用 argon2 库来散列和验证密码。我正在使用 @nestjs/passport 包提供的 LocalStrategy 来验证用户的凭据。

但是,我面临一个问题,即使密码正确,isPasswordValid 也始终为 false。我在 const isPasswordValid = await argon2.verify(user.password, password); 行设置了一个断点。并发现 isPasswordValid 始终未定义。我已验证用户对象正在从数据库中正确获取并且密码哈希值看起来相同。

bcrypt.compare() 也有同样的问题。

相关代码如下:


@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private userService: UsersService) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.userService.findOne(username);
    console.log('User found:', user);
    console.log('Provided password:', password);
    if (!user) {
      throw new UnauthorizedException();
    }
  
    const isPasswordValid = await argon2.verify(user.password, password); 
    console.log('Is password valid:', isPasswordValid);

    if (!isPasswordValid) {
      throw new UnauthorizedException();
    }
  
    return user;
  }
}

想知道如何解决这个问题

nestjs bcrypt
© www.soinside.com 2019 - 2024. All rights reserved.