【发布时间】: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);
}
【问题讨论】:
-
文档链接是什么?
-
这可能会让你走向正确的方向stackoverflow.com/questions/62799708/…
-
哦,我认为 Nest 需要一个名为 username 而不是凭据的字段。如果我想称它为凭据,我需要传递选项哟超级。谢谢!
-
如果解决了,请发表一个答案,这对以后的其他人会有帮助
标签: authentication passport.js nestjs passport-local nestjs-passport