How to decode jwt token in javascript without using a library?
Note: this does not validate the signature, it just extracts the JSON payload from the token, which could have been tampered with.
Browser
Working unicode text JWT parser function:
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
JWT uses base64url
(RFC 4648 §5), so using only atob
(which uses base64
) isn't enough.
Node.js
function parseJwt (token) {
return JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
}
How to decode a JWT token with TinyGo
Decoding and getting the name
part is easy. But this does not ensure the token is valid, meaning the owner of the token is truly what the name says!
JWT tokens just contain the base64 encoded forms of a header, payload and signature parts, connected with a .
. So just split the token by .
, decode the base64 string and you may use json.Unmarshal()
to convert the header and playload parts to maps or structs.
You must verify the signature to ensure the name is valid. If you don't perform signature verification, a token may easily be forged to pose as anyone. Signature verification is exactly what JWT libs do (besides parsing and generating tokens). How to do that, check the sources of JWT libs. I also believe there are open-source libs that process JWT tokens that also work with tiny-go.
Example code to decode the parts and print the name
:
token := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`
for i, part := range strings.Split(token, ".") {
fmt.Printf("[%d] part: %s\n", i, part)
decoded, err := base64.RawURLEncoding.DecodeString(part)
if err != nil {
panic(err)
}
fmt.Println("decoded:", string(decoded))
if i != 1 {
continue // i == 1 is the payload
}
var m map[string]interface{}
if err := json.Unmarshal(decoded, &m); err != nil {
fmt.Println("json decoding failed:", err)
continue
}
if name, ok := m["name"]; ok {
fmt.Println("name:", name)
}
}
Which outputs (try it on the Go Playground):
[0] part: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
decoded: {"alg":"HS256","typ":"JWT"}
[1] part: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
decoded: {"sub":"1234567890","name":"John Doe","iat":1516239022}
name: John Doe
[2] part: SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
decoded
How to decode jwt token in POSTMAN?
Postman supports cryptojs library : https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#using-external-libraries
Add below example to postman test script:
let jwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0.UsrGn95rk5DStcC_WwIr3WIv5rHe2IApX56I58l8uyo`
a = jwt.split('.');
//a.forEach(function (val) {
var words = CryptoJS.enc.Base64.parse(a[1]);
var textString = CryptoJS.enc.Utf8.stringify(words);
console.log(textString)
//})
Output:
The hmacSHA256 is not an encryption algorithm but an Hashing algorithm so there is no way to decode it as hashing is one-way function.
as the last part is in the form
HMACSHA256 of ( base64(header) + "." + base64(body) )
you can try creating it and equating both are equal
What's the best way to decode a JWT on Laravel / PHP?
You can use this package https://github.com/lcobucci/jwt to handle your jwt. It already provides a lot of tools.
If you're using Passport in your Lumen app it should be probably already available.
Decoding jwt token
You should move the console.log(jwt.decode(token))
inside the then
block or use an async
function:
import jwt from 'jsonwebtoken';
async function loginRequest() {
try {
const { data } = await axios.post(
'https://afe2021fitness.azurewebsites.net/api/Users/login',
state
);
const token = data.jwt;
localStorage.setItem('jwtToken', token);
console.log(token);
console.log(jwt.decode(token));
} catch (err) {
console.log(err);
}
}
How to properly extract payload from nestjs/jwt token?
You need to cast the type. Tell explicitly what type it is.
type PayloadType = {
email: string;
}
async refreshTokenByOldToken(authHeader: string) {
const decodedJwt = this.jwtService.decode(authHeader.split(' ')[1]) as PayloadType;
return decodedJwt.email
}
You can reference PayloadType
other places as well for example in your service instead of string | { [key: string]: any; }
you can have string | PayloadType
.
examples of type casting
Related Topics
Adding Your Own HTMLhelper in ASP.NET MVC 3
Turn a Simple C# Dll into a Com Interop Component
Xdocument Containing Namespaces
Are There Any Fuzzy Search or String Similarity Functions Libraries Written for C#
Passing Data Between Different Controller Action Methods
C# Using Reflection to Copy Base Class Properties
Differencebetween "X Is Null" and "X == Null"
Handling Unhandled Exceptions Problem
Scraping Webpage Generated by JavaScript with C#
Unzip Files Programmatically in .Net
Generating Dll Assembly Dynamically at Run Time
Deserializing Dates with Dd/Mm/Yyyy Format Using JSON.Net
How to Determine If a Type Implements a Specific Generic Interface Type
Merging Multiple PDFs Using Itextsharp in C#.Net