【问题标题】:NestJS JwtStrategy use configService to pass secret keyNestJS JwtStrategy 使用 configService 传递密钥
【发布时间】:2025-11-21 20:20:02
【问题描述】:

我有来自文档示例 (https://docs.nestjs.com/techniques/authentication) 的 JwtStrategy 类:

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(
        private readonly authService: AuthService,
        private readonly configService: ConfigService,
    ) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: this.configService.getSecretKey,
        });
    }
    // ...
}

当我在调用 super() 之前尝试访问 this 时出现错误。但我仍然想使用 configService 来获取密钥。

我知道我可以使用 env var 来做到这一点,但在我看来,服务方法是更清晰的解决方案。

如何使用 configService 或从中获取价值并传递给 super() 调用?谢谢。

【问题讨论】:

    标签: typescript nestjs passport-jwt


    【解决方案1】:

    只需删除this.,请参见此处:

    secretOrKey: configService.getSecretKey
    

    自从configService 已作为参数传递后,它将起作用。

    【讨论】:

    • 为了避免“声明了属性 'configService' 但从不读取其值。”我还不得不从private readonly configService: ConfigService 中删除private
    • 我可以确认,您不能有 private 关键字并在 constructor 内的 super() 调用中使用该属性