0
$\begingroup$

A JSON Web Token is supposed to have the following format:

token = encodeBase64(header) + '.' + encodeBase64(payload) + '.' + encodeBase64(signature)

When I use the jsonwebtoken node.js function to create a token:

jsonwebtoken.sign({username : "admin", password : "admin"}, publicKey, { algorithm:'HS256' });

It produces the following output:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiJhZG1pbiIsImlhdCI6MTY2OTIxMDE0MH0.Cj2-vgNkw2xChXMe5YjIrH9UYH6-pL7ArSERBVJO-zE

When you decode the header, you get:

'{"alg":"HS256","typ":"JWT"}'

But decoding the payload gives a padding error because the padding has been omitted. Only when the payload is changed to (correct number of '=' added):

eyJ1c2VybmFtZSI6ImFkbWluIiwicGFzc3dvcmQiOiJhZG1pbiIsImlhdCI6MTY2OTIxMDE0MH0=

Does it decode correctly to:

'{"username":"admin","password":"admin","iat":1669210140}'

And the signature cannot be decoded because it contains multiple '-', which is an invalid base64 character.

My question is this:

If each section is meant to be base64 encoded, then why is the padding ommitted from the payload, and what is the strange syntax of the signature?

I tried finding information on the jsonwebtoken GitHub repository , but couldn't find an explanation.

EDIT: After doing some more research, I discovered that JWT uses Base64URL encoding, not Base64 encoding. Will update this post once I have more information.

$\endgroup$

1 Answer 1

0
$\begingroup$

JWTs are not encoded in plain Base64, but in Base64url. For this version, padding is optional, and it uses different charset: '-' instead of '+' and '_' instead of '/'.

Sources:

https://jwt.io/introduction https://en.wikipedia.org/wiki/Base64#Variants_summary_table

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.