I'm working on a website that stores JWT token inside cookies. What I want to do is, create Javascript that decodes the token and extracts the value I need and pass it on to the another Javascript written by my co-worker. My question is, is there client-side javascript library for JWT token decoding that I can import from my script?
Asked
Active
Viewed 1.5k times
7
-
1Check this: https://jwt.io/#libraries Look for Javascript section – Mike Cheel Oct 12 '16 at 18:51
-
1@MikeCheel 's comment is very useful if you need to verify a signed JWT or decode a crypted JWT. But if you just want o read an uncrypted JWT, you just need to base64 decode it as described in the answer from bhspencer – Andreas Lundgren Oct 13 '16 at 19:25
-
Be careful, the user can tamper with that and since you don't have access to the shared secret on the backend, it won't be reliable ever. – aderchox Apr 14 '22 at 11:55
2 Answers
13
EDIT: It has come to my attention that this answer is incorrect. Please see this answer instead How to decode jwt token in javascript without using a library?
A JWT is just a dot separated base64 encoded string. You just need to split on the dots and then use atob() to decode. You don't need an external library.
e.g.
var jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";
var tokens = jwt.split(".");
console.log(JSON.parse(atob(tokens[0])));
console.log(JSON.parse(atob(tokens[1])));

bhspencer
- 13,086
- 5
- 35
- 44
-
-
@user30646 https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22 – Mike Cheel Oct 13 '16 at 19:36
-
This is missing validation. You should validate JWT's, anyone can create them, but only the person that knows the secret can create a token signed with the secret. – FastDeveloper Jan 10 '21 at 19:16
-
1The OP asked "What I want to do is, create Javascript that decodes the token and extracts the value I need". Of course it is also necessary to verify the signature on the token but that is outside the scope of this question. – bhspencer Jan 11 '21 at 20:40
-
2@FastDeveloper Validation occurs on server side, a secret on client side would defeat the purpose of jwt – Matías Cánepa Aug 23 '21 at 16:03
-
Not necessarily. The client could be verifying the token is from who they say they are with a public key. – bhspencer Aug 23 '21 at 19:00
2
https://github.com/auth0/jwt-decode : jwt-decode is a small browser library that helps decoding JWTs token which are Base64Url encoded.

Tanu
- 1,286
- 4
- 16
- 35