Javascript 雀巢公司+;Passport-JWTStrategy从不使用RS256令牌调用

Javascript 雀巢公司+;Passport-JWTStrategy从不使用RS256令牌调用,javascript,jwt,passport.js,nestjs,passport-jwt,Javascript,Jwt,Passport.js,Nestjs,Passport Jwt,我试图在nestjs后端实现RS256 JWT令牌。我遵循了中提供的示例 在我的模块中,我使用私钥注册JwtModule: @Module({ imports: [ PassportModule.register({ defaultStrategy: 'jwt' }), JwtModule.register({ secretOrPrivateKey: extractKey(`${process.cwd()}/keys/jwt.private.

我试图在nestjs后端实现RS256 JWT令牌。我遵循了中提供的示例

在我的模块中,我使用私钥注册
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;
   }
}
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: publicKey,
      algorithms: ['RS256'],
      ^^^^^^^^^^^^^^^^^^^^^^
    });
和保护端点:

@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
   }
}
@Controller('auth'))
导出类AuthController{
构造函数(私有只读authService:authService){}
@获取('令牌')

async createToken():Promise

您必须在
JwtModule
JwtStrategy
中指定RS256作为的算法:

@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;
   }
}
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: publicKey,
      algorithms: ['RS256'],
      ^^^^^^^^^^^^^^^^^^^^^^
    });


不确定它是否有效,但你可以试试这个

@UseGuards(AuthGuard('jwt'))

您的代码沙盒中的示例也适用于我。但它实现了常规HS256令牌。正如我在问题中所写的,问题是RS256令牌-因此使用RSA证书签名。请查看我的代码沙盒-我在问题中添加了一个链接。抱歉,我以前的回答不正确。请参阅我的EditException pro根据JwtModule和JwtStrategy中的算法名称,我只想补充一点,关键是密钥的格式必须正确。私钥和公钥必须都是RSA格式。我的公钥是以SSH2格式提供的,这就是它不起作用的原因。