【问题标题】:NestJS' Passport Local Strategy "validate" method never calledNestJS 的 Passport 本地策略“验证”方法从未被调用
【发布时间】:2021-09-11 06:17:06
【问题描述】:

我正在尝试实施 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;
  }
}

我的 AuthModule 导入:

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

示例用法:

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

【问题讨论】:

标签: authentication passport.js nestjs passport-local nestjs-passport


【解决方案1】:

validate 方法必须具有参数usernamepassword 参数必须匹配usernameFieldpasswordField 值在构造函数中传递给 super()。如果它们不匹配,validate 方法将不会被调用。我认为这是因为 Nest 调用了 validate(...args),但不是 100% 确定。

【讨论】:

    【解决方案2】:

    您似乎在这里缺少LocalAuthGuard 课程。你需要用这个类创建一个文件,然后..

    import { Injectable } from '@nestjs/common';
    import { AuthGuard } from '@nestjs/passport';
    
    @Injectable()
    export class LocalAuthGuard extends AuthGuard('local') {}
    

    这将使用本地守卫。

    【讨论】:

    • 我确实做到了。我只是没有把它包括在我的问题中,因为我不想让我的问题过于复杂
    猜你喜欢
    • 2017-05-25
    • 2022-07-19
    • 2023-04-05
    • 2019-03-19
    • 1970-01-01
    • 2020-06-09
    • 2021-12-15
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多