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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With