NestJS 的 Passport 本地策略“验证”方法从未被调用

Sku*_*ter 11 authentication passport-local passport.js nestjs nestjs-passport

我正在尝试实施护照本地策略,但验证方法不起作用。当我这样做时@UseGuards(AuthGuard("local")),它会自动抛出未经授权的异常,而无需通过我编写的验证方法。我不知道我做错了什么,因为文档也做了同样的事情。

这是我的LocalStrategy课程:

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(UserRepository) private userRepository: UserRepository,
  ) {
    super();
  }

  async validate(credentials: string, password: string): Promise<User> {
    // this method is never called, I've already did some console.logs
    const user = await this.userRepository.findByCredentials(credentials);

    if (!user) throw new UnauthorizedException('Invalid credentials');

    if (!(await argon2.verify(user.hash, password)))
      throw new UnauthorizedException('Invalid credentials');

    return user;
  }
}
Run Code Online (Sandbox Code Playgroud)

我的AuthModule导入:

@Module({
  imports: [TypeOrmModule.forFeature([UserRepository]), PassportModule],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)

用法示例:

  @Post("/login")
  @UseGuards(LocalAuthGuard)
  async login(@Body() loginDto: LoginDto) {
    return this.authService.login(loginDto);
  }
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 28

编辑

在花费更多时间编写代码并自己进行深入研究之后,事实上方法必须具有名为和 的validate参数,它们可以是和,但重要的您有两个属性和。如果你没有和,那么你将永远无法进入班级。 usernamepasswordbobalicereq.bodyusernamepasswordreq.body.usernamereq.body.passwordvalidateLocalStrategy


validate方法必须具有参数usernamepassword 并且/或参数必须与构造函数中传递的usernameField和值匹配。如果它们不匹配,则不会调用该方法。我认为这是由于 Nest 打电话的事实,但我不能 100% 确定。passwordFieldsuper()validatevalidate(...args)

  • 实际上,您可以将本地策略上的字段名称配置为您想要的。这可以通过调用 super() 并传递选项映射对象来完成。我们可以传递一个选项对象。这将定制护照策略的行为。在此示例中,默认情况下,passport-local 策略需要请求正文中包含名为“用户名”和“密码”的属性。传递一个 options 对象来指定不同的属性名称,例如:super({ usernameField: 'email' })。有关更多信息,请参阅护照文档。 (3认同)