我正在尝试在nestjs后端实现RS256 JWT令牌。我按照nestjs documentation提供的示例进行操作。
在我的模块中,我用我的私钥注册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时,我应该在控制台中看到至少我登录validate方法的“JwtStrategy”字符串。不幸的是它永远不会出现。为什么永远不会调用validate方法?
请在下面找到代码框
您必须在JwtModule
和JwtStrategy
中指定RS256作为算法:
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: publicKey,
algorithms: ['RS256'],
^^^^^^^^^^^^^^^^^^^^^^
});
和
JwtModule.register({
secretOrPrivateKey: privateKey,
signOptions: {
expiresIn: 3600,
algorithm: 'RS256',
^^^^^^^^^^^^^^^^^^^
},
}),