是否可以用指定值初始化守卫? 例如,当前的示例将不起作用:
@Module({
imports: [
CoreModule,
],
providers: [
{
provide: AuthGuard, // while using APP_GUARD works
useFactory: (configService: ConfigService) => {
return new AuthGuard(configService.get('some_key'));
},
inject: [ConfigService],
},
],
})
当使用 APP_GUARD
进行 provide
时,将使用配置值初始化守卫。因此它仅适用于全局范围,但不适用于 @UseGuards(AuthGuard)
最佳答案
这不起作用,因为守卫没有在模块中注册为提供者。它们由框架直接实例化。
您可以在防护中使用依赖注入(inject):
@Injectable()
export class MyAuthGuard {
constructor(private readonly configService: ConfigService) {
// use the configService here
}
}
和
@UseGuards(MyAuthGuard)
或者自己实例化守卫:
@UseGuards(new AuthGuard(configService.get('some_key')))
在AuthGuard
的特殊情况下,您可以在PassportModule
中设置defaultStrategy
。然后你就可以使用@UseGuards(AuthGuard())
PassportModule.register({ defaultStrategy: 'jwt'})
或异步:
PassportModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ defaultStrategy: configService.authStrategy}),
inject: [ConfigService],
})
关于javascript - 用值初始化 Guard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54548743/