I've got a requirement to decode jwt token which sent by API during login time. How to decode jwt token in angular?
I've got a requirement to decode jwt token which sent by API during login time. How to decode jwt token in angular?
We can decode JWT token in angular for that you need to have "@auth0/angular-jwt" npm module installed in your angular app. The decode of JWT has following steps
npm i @auth0/angular-jwt -simport { JwtModule } from "@auth0/angular-jwt";
under imports:[] section add thisJwtModule.forRoot({
config: {
tokenGetter: () => localStorage.getItem('access_token')
}
})
Code would look like below.
import { JwtHelperService } from '@auth0/angular-jwt';
constructor(private jwtHelper: JwtHelperService) {}
someMethod(){
const token = this.jwtHelper.decodeToken(localStorage.getItem('access_token'));
}
NOTE: JwtHelperService has other methods too, use according to your need.
I don't think an external module is necessary to decode a JWT token. It could be done with JS atob() function.
Here is a general function using JS atob() with Array#split, Array#map and Array#reduce
function decodeToken(token) {
const _decodeToken = (token) => {
try {
return JSON.parse(atob(token));
} catch {
return;
}
};
return token
.split('.')
.map(token => _decodeToken(token))
.reduce((acc, curr) => {
if (!!curr) acc = { ...acc, ...curr };
return acc;
}, Object.create(null));
}
Here is a working snippet
function decodeToken(token) {
const _decodeToken = (token) => {
try {
return JSON.parse(atob(token));
} catch {
return;
}
};
return token
.split('.')
.map(token => _decodeToken(token))
.reduce((acc, curr) => {
if (!!curr) acc = { ...acc, ...curr };
return acc;
}, Object.create(null));
}
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
console.log(decodeToken(token));
Working example: Stackblitz