nestjs中有解码JWT的native方法吗?

Is there a native method in nestjs to decode JWT?

在 nestjs 中,我通过创建有效负载对象并对其进行签名来创建 JWT(令牌)。像这样:

    const jwtPayload: JwtPayload = 
    {
      iss:                issuer,
      sub:                info,
      aud:                audience,
   // exp:                - populated by fn: this.jwtService.sign(payload),
   // iat:                - populated by fn: this.jwtService.sign(payload),
      jti:                'XXXX1234' 
    }

const signedJwtAccessToken: string = this.jwtService.sign(jwtPayload); 

Nest 将 jwtPayload 编码成字符串。

对于清理工作,我想知道 JWT 究竟何时到期。这会自动编码到 'signedJwtAccessToken' - 属性 .exp - 通过 .sign() 函数。

要在签名后立即访问它,需要对其进行解码。

signedJwtAccessToken 签名后立即用相同的方法对其进行解码的最简单方法是什么???

注:

当 JWT 从客户端返回时,nestjs 在访问 fn:validate() 时解码它,但我想在签名后立即解码 - 在将响应发送给客户端之前,类似于:

                            // signing - encoding
const signedJwtAccessToken: string = this.jwtService.sign(jwtPayload);

                            // decoding
const decodedJwtAccessToken: string = decodeJwt(signedJwtAccessToken);

                            // parsing back to an object
const updatedJwtPayload: JwtPayload  = JSON.parse(decodedJwtAccessToken);

                            // reading property of .exp
const expires = updatedJwtPayload.exp;

只需将其解码为普通的 jwt 令牌即可。如果使用 nestjs-jwt package, just call decode 函数:

const decodedJwtAccessToken: JwtPayload = this.jwtService.decode(signedJwtAccessToken);

const expires = decodedJwtAccessToken.exp;

或者只是将令牌解码为 base64 字符串

const base64Payload = signedJwtAccessToken.split('.')[1];
const payloadBuffer = Buffer.from(base64Payload, 'base64');
const updatedJwtPayload: JwtPayload = JSON.parse(payloadBuffer.toString()) as JwtPayload;
const expires = updatedJwtPayload.exp;