NestJs + Passport - JWTStrategy 永远不会用 RS256 令牌调用

jma*_*zur 2 javascript jwt passport.js nestjs passport-jwt

我正在尝试在 Nestjs 后端实现 RS256 JWT 令牌。我按照Nestjs 文档中提供的示例进行操作。

在我的模块中,我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 {}
Run Code Online (Sandbox Code Playgroud)

我能够调用 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;
   }
}
Run Code Online (Sandbox Code Playgroud)

和受保护的端点:

@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
   }
}
Run Code Online (Sandbox Code Playgroud)

我假设当我调用 auth/data 时,我应该在控制台中至少看到我在验证方法中登录的“JwtStrategy”字符串。不幸的是它从未出现。为什么从不调用 validate 方法?

请找到下面的代码和框

编辑 Nest.js JWT 身份验证

Kim*_*ern 6

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

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: publicKey,
      algorithms: ['RS256'],
      ^^^^^^^^^^^^^^^^^^^^^^
    });
Run Code Online (Sandbox Code Playgroud)

JwtModule.register({
  secretOrPrivateKey: privateKey,
  signOptions: {
    expiresIn: 3600,
    algorithm: 'RS256',
    ^^^^^^^^^^^^^^^^^^^
  },
}),
Run Code Online (Sandbox Code Playgroud)