我已逐步遵循官方 Nest 文档( https://docs.nestjs.com/security/authentication ),但在使用 @AuthGuard('local') 或 @AuthGuard 时无法调用 validate() 方法(LocalAuthGuard) 登录操作。
如果我不使用那个保护装饰器,一切都会按预期工作(但我需要使用它来将我的令牌添加到请求对象中)。
auth.controller.ts
@UseGuards(AuthGuard('local')) // or AuthGuard(LocalAuthGuard)
@Post('login')
async login(
@Request() req
) {
const { access_token } = await this.authService.login(req.user);
return access_token;
}
}
local.strategy.ts
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string): Promise<any> { // class is constructed but this method is never called
const user: UserDto = await this.authService.login({
email,
password,
});
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
auth.module.ts
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: "bidon",
signOptions: {
expiresIn: '3600',
},
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService, PassportModule, JwtModule],
controllers: [AuthController],
})
export class AuthModule {}
PS:我已经阅读了所有与堆栈溢出相关的帖子(例如:NestJS' Passport Local Strategy "validate" method never called)但他们没有帮助我。