Last active
July 25, 2018 09:04
-
-
Save hgouveia/968114fa83d6e91f0c3aefbe72477bb6 to your computer and use it in GitHub Desktop.
Very simple helper class to decode JWT token on javscript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
export class JWTHelper { | |
/** | |
* Decode a JWT token | |
* | |
* @static | |
* @param {string} token | |
* @throws Error | |
* @returns object|boolean | |
* @memberof JWTHelper | |
*/ | |
static decode(token) { | |
if (!token || token === '') { | |
throw new Error("Token is empty"); | |
} | |
const tokenParts = token.split('.'); | |
// This token is invalid | |
if (tokenParts.length < 3) { | |
throw new Error("Token is invalid"); | |
} | |
// 0 - header | |
// 1 - payload | |
// 2 - signature | |
// Decode from base64 to json string | |
let [header, payload, signature] = tokenParts | |
.map(parts => new Buffer(parts, 'base64').toString()); | |
// convert the json string to object | |
// this will throw error if fail on parsing | |
// but we dont wrap into try/catch, so the user | |
// could catch it themself | |
header = JSON.parse(header); | |
payload = JSON.parse(payload); | |
return { | |
header, | |
payload, | |
signature | |
}; | |
} | |
/** | |
* Checks if the token has expired | |
* | |
* @static | |
* @param {string} token | |
* @throws Error | |
* @returns boolean | |
* @memberof JWTHelper | |
*/ | |
static hasTokenExpired(token) { | |
const decodedToken = this.decode(token); | |
const payload = decodedToken.payload; | |
/* | |
Payload | |
{ | |
"iat": timestamp, | |
"exp": timestamp | |
} | |
*/ | |
if (payload.hasOwnProperty("exp")) { | |
const currentTime = new Date().getTime(); | |
const expTime = new Date(payload.exp * 1000).getTime(); | |
return (currentTime > expTime) | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment