Skip to content

Instantly share code, notes, and snippets.

@atultherajput
Created January 17, 2019 13:19
Show Gist options
  • Save atultherajput/5ed43400f310595359dd56127bc6df92 to your computer and use it in GitHub Desktop.
Save atultherajput/5ed43400f310595359dd56127bc6df92 to your computer and use it in GitHub Desktop.
JWT utility library for Angular 6
import { Injectable } from '@angular/core';
@Injectable()
export class JWTUtil {
constructor() { }
decodeToken(accessToken: string) {
let base64Url = accessToken.split('.')[1];
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
let JwtDecode = JSON.parse(window.atob(base64));
console.info("Decoded Token: ", JwtDecode);
return JwtDecode
}
expirationTime(accessToken: string): number {
let parseJwt = this.decodeToken(accessToken);
let expTime = parseJwt.exp;
return expTime
}
isExpired(accessToken: string): Boolean {
let expTime = this.expirationTime(accessToken);
console.log("Expiration time: ", expTime, new Date(expTime))
let currentTimeInMilli = new Date().getTime();
console.log("Current time: ", currentTimeInMilli, new Date(currentTimeInMilli))
if (expTime < currentTimeInMilli) {
console.warn("Token Expired!")
return true
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment