NestJS JWT 策略需要一个秘密或密钥

Rob*_*ley 8 authentication node.js jwt passport.js nestjs

在我的 NestJS 节点应用程序中,我已经使用 Passport 设置了 JWT 身份验证(根据https://docs.nestjs.com/techniques/authentication)但是我试图将 JWT 密钥保留在使用内置检索的环境文件中 -在配置服务中。

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('JWT_KEY'),
      signOptions: { expiresIn: '60s' }
    });
  }
Run Code Online (Sandbox Code Playgroud)

该模块注册如下:

JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        return {
          secret: configService.get<string>('JWT_KEY')
        };
      },
      inject: [ConfigService]
    })
Run Code Online (Sandbox Code Playgroud)

启动应用程序时出现以下错误:

api: [Nest] 16244   - 03/27/2020, 10:52:00   [ExceptionHandler] JwtStrategy requires a secret or key +1ms
Run Code Online (Sandbox Code Playgroud)

看起来 JWTStrategy 类在 ConfigService 准备好提供 JWT Key 之前正在实例化,并且在调用configService.get<string>('JWT_KEY').

我在这里做错了什么?在尝试检索任何环境变量之前,如何确保 ConfigService 已准备就绪?

更新:整个 AuthModule 如下:

api: [Nest] 16244   - 03/27/2020, 10:52:00   [ExceptionHandler] JwtStrategy requires a secret or key +1ms
Run Code Online (Sandbox Code Playgroud)

Jay*_*iel 19

我会愿意打赌,问题是,你是不是import荷兰国际集团的ConfigModuleAuthModule,而是要添加ConfigServiceproviders直接阵列。这意味着如果ConfigModule在 上进行任何设置ConfigService,它将不再发生。你应该拥有的是这样的:

@Module({
  imports: [
    PassportModule.register({defaultStrategy: 'jwt' }),
    UserModule,
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        return {
          secret: configService.get<string>('JWT_KEY')
        };
      },
      inject: [ConfigService]
    }),
    ConfigModule,
  ],
  providers: [LocalStrategy, JwtStrategy, AuthService],
  controllers: [AuthController],
  exports: [PassportStrategy],
})
export class AuthModule {}
Run Code Online (Sandbox Code Playgroud)

现在只要一个ConfigModule exports ConfigServiceAuthModule应该就可以正常启动了。

  • 我刚刚意识到 JWTStrategy 中有一个拼写错误。我把 JWT_KET 而不是 JWT_KEY...感谢大家的帮助。噢。*捂脸* (2认同)