Skip to content

Instantly share code, notes, and snippets.

@tiagorangel2011
Last active April 23, 2024 17:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagorangel2011/8db4ee6b9ef07624a66719861455332a to your computer and use it in GitHub Desktop.
Save tiagorangel2011/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")
}
}
@cmdwm
Copy link

cmdwm commented Mar 10, 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.

@tiagorangel2011
Copy link
Author

tiagorangel2011 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