JasonWebTokens (JWT) as we have learnt in authentication-with-nodejs-and-mongodb-part-3, enables us create a random token for a logged in user.
This token is made up of the user parameters we passed in while logging into the system like we have in this snippet from the article:
// create JWT token
const token = jwt.sign(
{
userId: user._id,
userEmail: user.email,
},
"RANDOM-TOKEN",
{ expiresIn: "24h" }
);
From the code snippet above, we passed in a userId
and userEmail
to create the JWT. When the token is created, we have a string like we find in the image below:
Decode the token
Sometimes, we might find ourselves in a situation where we need to get the details we passed in while creating that token. In this case we need to decode the token.
Assuming you have gotten the token, decode the token following these steps:
- create a function to accept the token
// create a function to accept the token
function parseJwt(token) {
}
- In the function, check if the token is valid. If it is not valid, terminate the operation with a
return
like so:
function parseJwt(token) {
// terminate operation if token is invalid
if (!token) {
return;
}
}
- Split the token and taken the second; pass it to a constant
(base64Url)
like so:
function parseJwt(token) {
// terminate operation if token is invalid
if (!token) {
return;
}
// Split the token and taken the second
const base64Url = token.split(".")[1];
}
- Replace
-
with+
;_
with/
inbase64Url
constant and assign it a new constant like so
function parseJwt(token) {
// terminate operation if token is invalid
if (!token) {
return;
}
// Split the token and taken the second
const base64Url = token.split(".")[1];
// Replace "-" with "+"; "_" with "/"
const base64 = base64Url.replace("-", "+").replace("_", "/");
}
- Finally, return the result parsed in JSON like so
function parseJwt(token) {
// terminate operation if token is invalid
if (!token) {
return;
}
// Split the token and taken the second
const base64Url = token.split(".")[1];
// Replace "-" with "+"; "_" with "/"
const base64 = base64Url.replace("-", "+").replace("_", "/");
}
// return the result parsed in JSON
return JSON.parse(window.atob(base64));
- Now you can just call on the function and pass in a token of your choice like so:
// loggedin user
const user = parseJwt(token)
Final Code
// decode the logged in user
function parseJwt(token) {
if (!token) {
return;
}
const base64Url = token.split(".")[1];
const base64 = base64Url.replace("-", "+").replace("_", "/");
return JSON.parse(window.atob(base64));
}
// loggedin user
const user = parseJwt(token)
Conclusion
Just as JWT gives us a way to encode data and make our system secured ad robust, we also have a way to decode it. This tutorial have no doubt shown us step by step how it works and how we can achieve it.
Thank you for reading.
Top comments (1)
JasonWebTokens 😂