假设我的模块定义如下:
@Module({
imports: [
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
// Use ConfigService here
secretOrPrivateKey: 'secretKey',
signOptions: {
expiresIn: 3600,
},
}),
PrismaModule,
],
providers: [AuthResolver, AuthService, JwtStrategy],
})
export class AuthModule {}
现在如何从这里的secretKey
中获得ConfigService
?
答案 0 :(得分:2)
您必须使用registerAsync
,以便可以注入ConfigService
。使用它,您可以导入模块,注入提供程序,然后在返回配置对象的工厂函数中使用这些提供程序:
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secretOrPrivateKey: configService.getString('SECRET_KEY'),
signOptions: {
expiresIn: 3600,
},
}),
inject: [ConfigService],
}),
有关更多信息,请参见async options docs。
答案 1 :(得分:0)
或者还有另一种解决方案,创建一个JwtStrategy类,如下所示:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.session.secret,
issuer: config.uuid,
audience: config.session.domain
});
}
async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
您可以将ConfigService
作为参数传递给构造函数,但是我仅从纯文件使用config。
然后,不要忘记将其放置在模块中的提供程序数组中。
致谢。