-
-
Save tiagorangel1/8db4ee6b9ef07624a66719861455332a to your computer and use it in GitHub Desktop.
// 💡 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") | |
} | |
} |
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
Possibly the encoding algorithm used in that JWT is different than the one the function tests for, apologies!
Can be done in 1 line, literally:
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.