如何在 Nest.JS 中使用多个 Secret 实现多个 JWT 策略 [英] How to implement multiple JWT strategies using multiple secrets in Nest.JS

查看:20
本文介绍了如何在 Nest.JS 中使用多个 Secret 实现多个 JWT 策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢实现多个命名的 passport-JWT 策略,每个策略都有自己的 secret.有什么办法可以实现吗?据我从 documentation 了解到,在模块初始化:

I like to implement more than one named passport-JWT strategy, each with its own secret. Is there any way it can be implemented? From what I can understand from the documentation, only one secret can be registered during module initialization:

@Module({
  imports: [
    UsersModule,
    PassportModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: '60s' },
    }),
  ],
  providers: [AuthService, LocalStrategy],
  exports: [AuthService, JwtModule],
})

推荐答案

为了允许注册同一服务的多个变体,您将需要在 JwtModule 周围使用自定义提供程序和包装器模块.它可能看起来像这样:

To allow for the registration of multiple variants of the same service, you're going to need to use a custom provider and wrapper module around the JwtModule. It would probably look something like this:

@Module({
  imports: [JwtModule.register({
    secret: secret1,
    signOptions: { expiresIn: '60s' },
  })],
  providers: [{
    provide: 'JwtSecret1Service',
    useExisting: JwtService,
  }],
  exports: ['JwtSecret1Service'],
})
export class JwtSecret1Module {}

现在您可以使用 @Inject('JwtSecret1Service') 来使用此特定配置,只要将 JwtSecret1Module 添加到 imports消费模块.您可以根据需要使用尽可能多的 JwtService 变体,每个变体都有自己的配置

Now you can use @Inject('JwtSecret1Service') to use this specific configuration so long as JwtSecret1Module has been added to the imports of the consuming module. You can do this with as many variants of the JwtService as you want, and each one will hold it's own configuration

这篇关于如何在 Nest.JS 中使用多个 Secret 实现多个 JWT 策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆