Question3r
Question3r

Reputation: 3772

extract the expiration datetime from jsonwebtoken

To invalidate a token it's as far as I know the best way to store the token and it's expiration datetime to the database. To validate it, you simply have to select it from the database and if it exists, you know it was invalidated. Further you can remove every expired token by it's expiration datetime from the database.

So I created a middleware that extracts the token from the authorization headers and it should attach the token and the expiration datetime to the request object. The datetime is required for the signOut route to invalidate the token.

  async use(req: any, res: Response, next: NextFunction) {
    try {
      const headers: IncomingHttpHeaders = req.headers;
      const authorization: string = headers.authorization;
      const bearerToken: string[] = authorization.split(' ');
      const token: string = bearerToken[1];

      if (await this.authenticationsRepository.findByEncodedToken(token)) { // invalidated token?
        throw new Error(); // jump to catch
      }

      req.tokenPayload = verifyToken(token); // calls jwt.verify with secret
      next();
    } catch (error) {
      throw new UnauthorizedException();
    }
  }

But how can I extract the exp attribute from the token to calculate the expiration date time?

Upvotes: 1

Views: 3121

Answers (1)

Safeer Raees
Safeer Raees

Reputation: 410

In order to get expiration date you need to decode the jsonwebtoken and access it's exp key, kind of like this:

let token = jwt.sign({
    data: 'foobar'
}, 'secret', { expiresIn: '1h' });


var decoded = jwt.decode(token, { complete: true });
console.log(decoded.payload.exp);

In your case you can do it like this I think:

req.expirationTime = jwt.decode(token, { complete: true }).payload.exp;

Upvotes: 6

Related Questions