Skip to content

Instantly share code, notes, and snippets.

@tiagorangel1
Last active April 23, 2024 17:58
Show Gist options
  • Save tiagorangel1/8db4ee6b9ef07624a66719861455332a to your computer and use it in GitHub Desktop.
Save tiagorangel1/8db4ee6b9ef07624a66719861455332a to your computer and use it in GitHub Desktop.
JWT decoder used for Authflow
// 💡 Tip: need to decode with node.js? Use the @authflow-js/verify npm module
function decryptJWT(e) {
function b64(e) {
return decodeURIComponent(Array.prototype.map.call(atob(e), function (e) {
return "%" + ("00" + e.charCodeAt(0).toString(16)).slice(-2)
}).join(""))
}
try {
const r = e
.split(".")[0]
.replace("-", "+")
.replace("_", "/"),
b64
c = (JSON.parse(b64(r)), e.split(".")[1].replace("-", "+").replace("_", "/"));
return JSON.parse(b64(c))
} catch (e) {
throw new Error("Invalid JWT")
}
}
@tiagorangel1
Copy link
Author

tiagorangel1 commented Mar 12, 2023

Can be done in 1 line, literally:

function jwt(token) { try {return JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()); } catch { return 'Error' } }

Obviously not the best but seems like you're using try; catch too, so it works. If it can't decode, or it's not an actual JWT it just returns Error. Much easier than what you had, didn't test your code but if it works better than this one that's great. Made the code above for my web app a few months ago and no issues so far.

@cmdwm Thx, checking it out!
EDIT: After some simple tests it failed with "Error". Anyway, thanks for the suggestion! Valid JWT used for testing: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

@cmdwm
Copy link

cmdwm commented Mar 15, 2023

Possibly the encoding algorithm used in that JWT is different than the one the function tests for, apologies!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment