Last active
September 19, 2017 13:11
-
-
Save katowulf/6231937 to your computer and use it in GitHub Desktop.
Deconstruct a JWT token for Firebase
This file contains hidden or 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
// Helper function to extract claims from a JWT. Does *not* verify the | |
// validity of the token. | |
// credits: https://github.com/firebase/angularFire/blob/master/angularFire.js#L370 | |
// polyfill window.atob() for IE8: https://github.com/davidchambers/Base64.js | |
// or really fast Base64 by Fred Palmer: https://code.google.com/p/javascriptbase64/ | |
function deconstructJWT(token) { | |
var segments = token.split("."); | |
if (!segments instanceof Array || segments.length !== 3) { | |
throw new Error("Invalid JWT"); | |
} | |
var claims = segments[1]; | |
return JSON.parse(decodeURIComponent(escape(window.atob(claims)))); | |
} |
This file contains hidden or 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
// Moment: http://momentjs.com/ | |
function tokHasTimeLeft(tok) { | |
if( !tok ) {return false;} | |
try { | |
var parts = deconstructJWT(tok); | |
// default is 24 hrs | |
var exp = parts.exp? moment.unix(parts.exp) : moment.unix(parts.iat).add('hours', 24); | |
// returns true if token has at least 12 hours left | |
return exp.diff(moment(), 'hours') > 12; | |
} | |
catch(e) { | |
console.warn(e); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, you might want to convert from base64url character set to tandard base64 character by adding this:
sources: