NestJS JwtStrategy 使用 configService 传递秘钥

Vla*_*kov 3 typescript nestjs passport-jwt

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

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

当我this在调用 super() 之前尝试访问时,出现错误。但我还是想用 configService 来获取秘钥。

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

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

Kam*_*iec 10

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

secretOrKey: configService.getSecretKey
Run Code Online (Sandbox Code Playgroud)

它将工作,因为configService已作为参数传递。

  • 避免“声明了属性“configService”,但从未读取其值。” 我还必须从“private readonly configService: ConfigService”中删除“private”。 (3认同)
  • 要添加上述答案和评论,请将“private”替换为“protected” (2认同)