How to check if JWT token is expired in Angular 8

Viewed 34061

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.

4 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
  }
}

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

I implemented something like this in my app and it works fine :

this.userToken$.pipe(
            filter((token: AuthToken) => !!token),
            map((token: AuthToken) => token.expiresIn()),
            tap((expiresIn: number) => console.log('token expires in', expiresIn / 1000 / 60, 'minutes')),
            switchMap((expiresIn: number) => timer(expiresIn)),
        ).subscribe(() => {
            console.warn('token expires');
            this.logout();
        });

This way, the user is not logged out once he tries to execute a new request but as soon as the token expires.

    const jwtToken = JSON.parse(atob(response.jwtToken.split('.')[1]));
    const expires = new Date(jwtToken.exp * 1000);
    const timeout = expires.getTime() - Date.now();
    setTimeout(() => this.logout(strategyName), timeout);

I implemented this using setTimeout and it will automatically logout when the token expires

Related