Created
April 28, 2022 04:44
-
-
Save thebearingedge/1b9a9dfbc41b6a614869b45b87dafc78 to your computer and use it in GitHub Desktop.
Decode a JSON Web Token in the browser.
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
function decode(token) { | |
const [, payload] = token.split('.') | |
try { return JSON.parse(atob(payload)) } catch (err) {} | |
const unsafe = payload.replace(/-/g, '+').replace(/_/g, '/') | |
let padded = unsafe + '='.repeat(4 - unsafe.length % 4) | |
const uriComponent = atob(padded).replace(/(.)/g, (_, c) => { | |
const hex = c.charCodeAt(0).toString(16).toUpperCase() | |
return '%' + (hex.length < 2 ? '0' : '') + hex | |
}) | |
return JSON.parse(decodeURIComponent(uriComponent)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment