我正在尝试实施 Passport 本地策略,但 validate 方法不起作用。当我执行@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);
}