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

时间:2019-03-10 19:47:16

标签: javascript jwt passport.js nestjs passport-jwt

我正在尝试在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方法?

请在下面找到代码和框

Edit Nest.js JWT Auth

2 个答案:

答案 0 :(得分:0)

您必须在JwtModuleJwtStrategy中都将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',
    ^^^^^^^^^^^^^^^^^^^
  },
}),

答案 1 :(得分:0)

不确定是否可以,但是您可以尝试

exports.handler = function(event, context) {
  context.succeed({
    statusCode: 200, 
    headers: {'content-type': 'text/html'}, 
    body: "<h1>bleh</h1>"
  });
};

高于您的受保护路线。