最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

初始化后卫值

运维笔记admin6浏览0评论

初始化后卫值

初始化后卫值

是否有可能与一个特定的值来初始化后卫?例如,当前示例将无法正常工作:

@Module({
  imports: [
    CoreModule,
  ],
  providers: [
    {
      provide: AuthGuard, // while using APP_GUARD works
      useFactory: (configService: ConfigService) => {
        return new AuthGuard(configService.get('some_key'));
      },
      inject: [ConfigService],
    },
  ],
})

在使用APP_GUARDprovide将与初始化配置值的后卫。因此,它仅适用于全球范围内,但不适合@UseGuards(AuthGuard)

回答如下:

这不起作用,因为警卫没有注册为模块供应商。他们得到直接由框架实例化。

您可以使用依赖注入在中后卫:

@Injectable()
export class MyAuthGuard {
  constructor(private readonly configService: ConfigService) {
    // use the configService here
  }
}

@UseGuards(MyAuthGuard)

或者你自己的实例后卫:

@UseGuards(new AuthGuard(configService.get('some_key')))

AuthGuard的特殊情况下,可以设置在defaultStrategy一个PassportModule。然后,你可以只使用@UseGuards(AuthGuard())

PassportModule.register({ defaultStrategy: 'jwt'}) 

或异步:

PassportModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({ defaultStrategy: configService.authStrategy}),
  inject: [ConfigService],
}) 

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论