Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if JWT token is expired in Angular 8

In Angular 8 what are different ways to check if the JWT token has expired. The expiry time is 1 hour. working code/samples will be highly appreciated.

like image 606
Pinnu Avatar asked Mar 19 '20 13:03

Pinnu


2 Answers

Option 1 - Manual

Token expiry time is encoded in the token in UTC time format. So it can be fetched and checked manually against current time in UTC. Try the following

private tokenExpired(token: string) {
  const expiry = (JSON.parse(atob(token.split('.')[1]))).exp;
  return (Math.floor((new Date).getTime() / 1000)) >= expiry;
}

ngOnInit() {
  if (this.tokenExpired(token)) {
    // token expired
  } else {
    // token valid
  }
}

Option 2 - Using JwtHelperService

You could use the JwtHelperService's isTokenExpired() method to check if the token has expired already.

import {JwtHelperService} from '@auth0/angular-jwt';
.
.
constructor(private jwtHelper: JwtHelperService) { }

ngOnInit() {
  if (this.jwtHelper.isTokenExpired(token)) {
    // token expired 
  } else {
    // token valid
  }
}
like image 157
ruth Avatar answered Sep 25 '22 14:09

ruth


You can get token expiry date with Angular-JWT package

 getTokenExpirationDate(token: string): Date {
    const decodedToken = helper.decodeToken(token);

    if (decodedToken.exp === undefined) { return null; }

    const date = new Date(0);
    date.setUTCSeconds(decodedToken.exp);
    return date;
  }
like image 44
parrycima Avatar answered Sep 22 '22 14:09

parrycima