我正在尝试在 Nestjs 后端实现 RS256 JWT 令牌。我按照中提供的示例进行操作Nestjs 文档 https://github.com/nestjs/nest/tree/master/sample/19-auth.
在我的模块中我注册了JwtModule
用我的私钥:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.key`),
signOptions: {
expiresIn: 3600,
},
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, HttpStrategy],
})
export class AuthModule {}
我能够调用 auth/token 端点并获取令牌,但是当我尝试访问受保护的端点时,我总是收到 401。
下面你可以找到我的定制JwtStrategy
:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: extractKey(`${process.cwd()}/keys/jwt.public.key`),
});
}
async validate(payload: JwtPayload) {
console.log('JwtStrategy');
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
和受保护的端点:
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Get('token')
async createToken(): Promise<any> {
return await this.authService.createToken();
}
@Get('data')
@UseGuards(AuthGuard())
findAll() {
console.log('Guarded endpoint');
// This route is restricted by AuthGuard
// JWT strategy
}
}
我假设当我调用 auth/data 时,我应该在控制台中至少看到我在验证方法中登录的“JwtStrategy”字符串。不幸的是它从未出现。为什么从不调用 validate 方法?
请找到下面的代码和框