JSON Web Tokens (JWT) are commonly used in single page application frameworks like Angular for authentication and authorisation. In situations where you want grab the details of the user from the token, you need a way to decode it yourself.

In this post, I will be using jwt-decode, which is an open-source library to decode JWT tokens.

What’s a JSON Web Token

A JWT is simply a long string value, which is represents a JSON object with all the information about a user. Often, JWTs are initially generated by APIs and passed to the client to help authenticate subsequent requests. 

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.

They 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.

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 JWT

We can easily decode a JWT using the jwt-decode library.

First, install the package via NPM:

npm install jwt-decode --save
Code language: Bash (bash)

Simply import the dependency in your service:

import * as jwt_decode from 'jwt-decode';
Code language: TypeScript (typescript)

You can now decode the token like so:

var token = 'eyJ0eXAiO... /// jwt token'; var decoded = jwt_decode(token); console.log(decoded); // Output: { "nameid": "5293518a-7940-47af-a807-5459dbb0ee21", "sub": "[email protected]", "jti": "dec3da1a-0510-4b21-99a6-fc82abb4debc", "unique_name": "[email protected]", "family_name": "Doe", "given_name": "John", "company_id": "7236", "exp": 1642370653, "iss": "API.Live", "aud": "Client.Live" }
Code language: TypeScript (typescript)

The output is a JSON object, containing the full details about the user.

var givenName = decodedToken['given_name'];
Code language: TypeScript (typescript)

The decoded value is persisted on the client application, to be sent in the Authorization header in subsequent requests to the API.

For example, we can choose to store it in localStorage so that it is accessible across different browser tabs:

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);
Code language: TypeScript (typescript)

So there you have it! We just used the jwt-decode library to decode a JSON Web Token. This allows us to extract user details, which can be useful for identifying the specific information such as role details.

Umut Esen

I am a software developer and blogger with a passion for the world wide web.

Leave a Reply

This Post Has 3 Comments

  1. Karthik

    what is wrong in using JSON.parse(atob(token.split(‘.’)[1])) ?

    1. Umut Esen

      Thanks for the suggestion, I prefer to use a library that is tried and tested instead of creating code and maintaining it.

  2. Edwin Moreno

    Hi!

    is there a way to verify the token signature by using a public key?

    use case: verify token signature with public key from angular to give access or deny using guard

    Thank you!