import { Injectable } from '@angular/core' ; @ Injectable ( ) export class JwtHelper { urlBase64Decode ( str ) { let output = str . replace ( /-/g , '+' ) . replace ( /_/g , '/' ) ; switch ( output . length % 4 ) { case 0 : { break ; } case 2 : { output += '==' ; break ; } case 3 : { output += '=' ; break ; } default : { throw new Error ( 'Illegal base64url string!' ) ; } } return this . b64DecodeUnicode ( output ) ; } b64decode ( str ) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' ; let output = '' ; str = String ( str ) . replace ( /=+$/ , '' ) ; if ( str . length % 4 === 1 ) { throw new Error ( 'atob failed: The string to be decoded is not correctly encoded.' ) ; } for ( let bc = 0 , bs = void 0 , buffer = void 0 , idx = 0 ; buffer = str . charAt ( idx ++ ) ; ~ buffer && ( bs = bc % 4 ? bs * 64 + buffer : buffer , bc ++ % 4 ) ? output += String . fromCharCode ( 255 & bs >> ( - 2 * bc & 6 ) ) : 0 ) { buffer = chars . indexOf ( buffer ) ; } return output ; } b64DecodeUnicode ( str ) { return decodeURIComponent ( Array . prototype . map . call ( this . b64decode ( str ) , function ( c ) { return '%' + ( '00' + c . charCodeAt ( 0 ) . toString ( 16 ) ) . slice ( - 2 ) ; } ) . join ( '' ) ) ; } decodeToken ( token ) { const parts = token . split ( '.' ) ; if ( parts . length !== 3 ) { throw new Error ( 'JWT must have 3 parts' ) ; } const decoded = this . urlBase64Decode ( parts [ 1 ] ) ; if ( ! decoded ) { throw new Error ( 'Cannot decode the token' ) ; } return JSON . parse ( decoded ) ; } }