Skip to content

Instantly share code, notes, and snippets.

@yimengtianya
Created October 13, 2015 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yimengtianya/283d14243ea9f41ccbc9 to your computer and use it in GitHub Desktop.
Save yimengtianya/283d14243ea9f41ccbc9 to your computer and use it in GitHub Desktop.
Wilddog:解析jwt token
// Helper function to extract claims from a JWT. Does *not* verify the
// validity of the token.
// 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))));
}
// Moment: http://momentjs.com/
function tokHasTimeLeft(tok) {
if( !tok ) {return false;}
try {
var parts = deconstructJWT(tok);
console.log(parts);
// default is 24 hrs
var exp = parts.exp? moment.unix(parts.exp) : moment.unix(parts.iat).add(24,'hours');
console.log(exp);
// 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