Reputation: 265
My app is currently running on expo and I need a way to decode JWT token I received from the backend. When I use jwt.io
it doesn’t need a key to decode, but I can’t seem to find a library supporting expo that doesn’t need a key to decode. I have tried decoding it without library using the code below but it doesn't work:-
JSON.parse(new Buffer(token.split(‘.’)[1], ‘base64’.toString()));
I have tried using a few expo libraries, but all that I found needs a key to decode and if I pass an empty string to the key it just wouldn't decode. I have also tried to decode without a library
The expected results is the object below after decoding my JWT token through jwt.io
:
{
"id": "5ce667c89133fd61e7f08c53",
"name": "TEST Group",
"username": "[email protected]",
"type": "G",
"iat": 1560152565
}
Is there any other way for me to decode without a key by using or without using a library in React Native on Expo?
Upvotes: 2
Views: 4652
Reputation: 31
My solution
1/ npm install buffer
2/ import { Buffer } from "buffer"
3/ const parts = responseJson.token.split('.').map((part) => Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'),'base64').toString());
Upvotes: 3
Reputation: 328
The JWT key is only here to sign the token, so yes can extract the data without the key.
The only thing you are missing is that buffers are not encoded in Base64 but in "URL Base64".
Before passing token parts to Buffer
you have to replace all '-' by '+' and all '_' by '/'.
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
const parts = token.split('.').map(part => Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString());
const payload = JSON.parse(parts[1]);
console.log('JWT payload', payload);
Upvotes: 7