1import { Injectable } from '@angular/core';
2import * as jwt_decode from 'jwt-decode';
3
4@Injectable()
5export class JWTTokenService {
6
7 jwtToken: string;
8 decodedToken: { [key: string]: string };
9
10 constructor() {
11 }
12
13 setToken(token: string) {
14 if (token) {
15 this.jwtToken = token;
16 }
17 }
18
19 decodeToken() {
20 if (this.jwtToken) {
21 this.decodedToken = jwt_decode(this.jwtToken);
22 }
23 }
24
25 getDecodeToken() {
26 return jwt_decode(this.jwtToken);
27 }
28
29 getUser() {
30 this.decodeToken();
31 return this.decodedToken ? this.decodedToken.displayname : null;
32 }
33
34 getEmailId() {
35 this.decodeToken();
36 return this.decodedToken ? this.decodedToken.email : null;
37 }
38
39 getExpiryTime() {
40 this.decodeToken();
41 return this.decodedToken ? this.decodedToken.exp : null;
42 }
43
44 isTokenExpired(): boolean {
45 const expiryTime: number = this.getExpiryTime();
46 if (expiryTime) {
47 return ((1000 * expiryTime) - (new Date()).getTime()) < 5000;
48 } else {
49 return false;
50 }
51 }
52}
53
1import jwt_decode from "jwt-decode";
2var token = "eyJ0eXAiO...";
3var decoded = jwt_decode(token);
4console.log(decoded);
5
6/* prints: * { foo: "bar", * exp: 1393286893, * iat: 1393268893 } */
1let b64DecodeUnicode = str =>
2 decodeURIComponent(
3 Array.prototype.map.call(atob(str), c =>
4 '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
5 ).join(''))
6
7let parseJwt = token =>
8 JSON.parse(
9 b64DecodeUnicode(
10 token.split('.')[1].replace('-', '+').replace('_', '/')
11 )
12 )