Angular – How to check if JWT token is expired in Angular 8

angularjwt-auth

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.

Best Answer

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
  }
}
Related Topic