Decode JSON Web Tokens (JWT) in Angular

JSON Web Tokens (JWT) are commonly used in single page application frameworks like Angular for authentication and authorisation due to their small size and high security. A JWT token can store a lot of information and we need a way to decode this token easily. Unfortunately, Angular does not offer a way to decode JWT tokens out-of-the-box but we can use an open-source library to do this. In this post, we will first look at the structure of a JWT token and show how to decode it in Angular using jwt-decode from npm.

What’s a JWT Token?

A JWT token is a JSON object, which contains all the required information about a user. JWT tokens are small in size for transmission and are also secure due to the algorithms (HMAC, RSA) used to sign them. These reasons make JWT tokens a very attractive option for modern web & mobile applications.

In a typical client-server architecture, the client gets the token from the server and keeps it locally. The token would be embedded it in each request that requires authentication. A JWT token consists of three parts: header, payload and signature. Here is an example token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1laWQiOiJmNjIxM2JjMC03OThlLTRmNWEtOGRiYy03ZWY2NmVkOTAzODQiLCJzdWIiOiJqb2guZG9lQG9udGhlY29kZS5jby51ayIsImp0aSI6IjdjZWI2Y2M2LTcxZDEtNGE1NS1hMDg1LTQ5ZWIwMjM5YjM0MyIsInVuaXF1ZV9uYW1lIjoiam9oLmRvZUBvbnRoZWNvZGUuY28udWsiLCJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2NsYWltcy9yb2xlIjoiQWRtaW4iLCJleHAiOjE1NDkyMjQ2NDYsImlzcyI6IlRPRE9BUFAuQVBJLkxpdmUiLCJhdWQiOiJUT0RPQVBQLkNsaWVudC5MaXZlIn0.IvDbQGRwsBiJfo76aRKzBRz1bujEO_k_W8VzlfMSL5E

As we can see above, each part of the token is separated with a dot.

  • Header contains the algorithm and token type of the token.
  • Payload contains all details about the user.
  • Signature is for verifying the identity of the sender and ensure the message was not modified during transmission.

Stick the example token above into the online converter and we get the following:

{ “alg”: “HS256”,“typ”: “JWT”},
{ “nameid”: “f6213bc0-798e-4f5a-8dbc-7ef66ed90384”,
    “sub”: “[email protected]”,
    “jti”: “7ceb6cc6-71d1-4a55-a085-49eb0239b343”,
    “unique_name”: “[email protected]”,
    “family_name”: “Doe”,
    “given_name”: “John”,
    “http://schemas.microsoft.com/ws/2008/06/identity/claims/role”: “Admin”,
    “exp”: 1549224646,
    “iss”: “TODOAPP.API.Live”,
    “aud”: “TODOAPP.Client.Live”}

HMACSHA256(base64UrlEncode(header) + “.” +   base64UrlEncode(payload), secret-key)

How to Decode a JWT Token

We can easily decode a JWT token in Angular using the jwt-decode library. Firstly, install the package into your project:

npm install jwt-decode --save

Simply import the dependency in your service:

import * as jwt_decode from 'jwt-decode';

You can now decode the token like so:

var token = 'eyJ0eXAiO... /// jwt token';
var decoded = jwt_decode(token); 
console.log(decoded);   

/* prints:  
* { foo: "bar", 
*   exp: 1393286893, 
*   iat: 1393268893  }  
*/

The library converts the given token into a stringified JSON object. decoded variable above is a JSON object, containing the full details about the user. Like any JSON object, we can extract details by specifying a property:

var givenName = decodedToken['given_name'];

You can create a custom JSON object and store it in local storage:

var currentUser = JSON.stringify({ 
    isAdmin: 'Admin' === decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'],
    id: decodedToken['nameid'],
    fullName: `${decodedToken['given_name']} ${decodedToken['family_name']}`});

localStorage.setItem('currentUser',currentUser);

Summary

In conclusion, we used the jwt-decode library to translate a JWT token into JSON. This allows us to extract frequently used details about the user like name, email and expiration date.

Umut Esen

Umut is an enthusiastic software developer, latest web and mobile technology adapter and primary author of onthecode.

Leave a Reply

Close Menu