Search code examples
jwtnestjsnestjs-passportnestjs-jwt

Is there a native method in nestjs to decode JWT?


In nestjs I create JWT (tokens) by creating a payload object and signing it. Something like this:

    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 encodes the jwtPayload into a string.

For cleanup work I would like to know when exactly the JWT expires. This is automatically encoded into the 'signedJwtAccessToken' - property .exp - by the .sign() function.

To access it right after the signing, it needs to be decoded.

What would be the simplest way to decode the signedJwtAccessToken in the same method right after it has been signed ???

Note:

When the JWT comes back from client, nestjs decodes it when accessing the fn: validate(), but I want to decode right after signing it - before sending the response to client, something like:

                            // 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;

Solution

  • Just decode it as a normal jwt token. If you use nestjs-jwt package, just call decode function:

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

    Or just decode the token as a base64 string

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