gpt4 book ai didi

javascript - 用值初始化 Guard

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:09 24 4
gpt4 key购买 nike

是否可以使用特定值初始化守卫?例如,当前示例将不起作用:

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

最佳答案

这不起作用,因为守卫没有在模块中注册为提供者。它们由框架直接实例化。

你可以在守卫中使用依赖注入(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com