初始化后卫值

问题描述 投票:2回答:2

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

@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)

javascript node.js typescript nestjs
2个回答
1
投票

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

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

@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
投票

我会尝试HT更简洁的方式,直接以这样的方式注入的ConfigService到AuthGuard:

@Module({
  imports: [
    CoreModule,
  ],
  providers: [
    AuthGuard,
  ],
  exports: [
    AuthGuard,
  ],
})
@Injectable()
export default class AuthGuard {
  constructor (protected readonly config: ConfigService) {
  }
  /*
  ...
  */
}
© www.soinside.com 2019 - 2024. All rights reserved.