Decoding a JWT token in?NodeJS
Vinod Kumar Nair
Cloud Architect (AWS) | CNCF Kubestronaut | SaaS | OpenSource Contributor | Blogger | DoKC Ambassador
JWT (or JSON Web Tokens) are an open, industry standard RFC 7519 method for representing claims securely between two parties.
It carries a lot of information in the encoded form in a HTTP/HTTPS request after a successful authentication. For instance, when we talk about multi-tenant cloud, a JWT can contain a domain/tenant information, JWT expiration details and/or subject in its body part. But wait? What does a body part looks like in a JWT Payload structure.
JWT payload structure:-
Here, if you look at carefully, JWT has three parts in it separated by a dot (.), whereas first part (in red) specifies header information, followed by body part (in pink) and then followed by signature (in blue).
Good thing about JWT is that it encodes the entire payload itself before it is transmitted over the network.
Let’s look at how you can decode it in NodeJS using Buffer library:-
const decodingJWT = (token) => { console.log(‘decoding JWT token’); if(token !== null || token !== undefined){ const base64String = token.split(‘.’)[1]; const decodedValue = JSON.parse(Buffer.from(base64String, ‘base64’).toString(‘ascii’)); console.log(decodedValue); return decodedValue; } return null; } module.exports.authorizer = async (event, context, callback) => { let token = null; if (event.queryStringParameters && event.queryStringParameters.token) { token = event.queryStringParameters.token; } const decodedJWT = decodingJWT(token); console.log(decodedJWT); }
There is no need of require while using the Buffer library as it is a global object. Buffer created with strings can take an optional encoding parameter to specify what encoding the string is in.
The available toString and Buffer constructor encodings are as follows:-
‘ascii’ — for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set.
‘utf8’ — Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
‘ucs2’ — 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual Plane, U+0000 — U+FFFF).
‘base64’ — Base64 string encoding.
‘binary’ — A way of encoding raw binary data into strings by using only the first 8 bits of each character.
Please do share your feedbacks.
Cheers
HRIS Business Analyst at Chevron
2 年Thanks so much, been looking for a much more simplified way to do this without using jose npm package
Cloud Architect (AWS) | CNCF Kubestronaut | SaaS | OpenSource Contributor | Blogger | DoKC Ambassador
4 年.