How to Get Claim Value from JWT String in Angular

JSON Web Tokens (JWT) are widely used for authentication and authorization purposes in web applications.

This article will demonstrate how to extract claim values from a JWT string in an Angular application.

We’ll walk you through the entire process, including setting up an Angular project, adding the necessary libraries, and creating a service to handle JWT operations.

JWT is a compact, URL-safe means of representing claims to be transferred between two parties. It allows for secure transmission of information as JSON objects, which are digitally signed using a secret key or a public/private key pair.

When a user logs into an application, the server issues a JWT token containing user information or other claims. The client then uses this token to access protected resources on the server.

 

How to Get Claim Values from JWT Token in Angular App?

Follow these steps to fetch the claims values like username, email address and other profile or access details from JWT token:

 

Setting up Angular project

Installing Angular CLI

Before we can start working on our Angular project, we need to install the Angular CLI globally:

npm install -g @angular/cli

 

Creating a new Angular project

Next, let’s create a new Angular project by running the following command:

ng new jwt-angular-demo
cd jwt-angular-demo

 

Adding Angular JWT library

To handle JWT operations in Angular, we will use the @auth0/angular-jwt library. Install it by running:

npm install @auth0/angular-jwt

 

Creating a JWT service

Decoding JWT tokens

We’ll create a JWT service to handle decoding JWT tokens and extracting claim values. First, generate a new service:

ng generate service jwt

 

Next, update the jwt.service.ts file with the following code:

import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable({
  providedIn: 'root'
})
export class JwtService {
  private jwtHelper: JwtHelperService;

  constructor() {
    this.jwtHelper = new JwtHelperService();
  }

  public decodeToken(token: string): any {
    return this.jwtHelper.decodeToken(token);
  }
}

 

Extracting claims from JWT string

To extract claim values from the JWT string, we’ll add a getClaim method to the JwtService. Update the jwt.service.ts file with the following code:

public getClaim(token: string, claimKey: string): any {
  const decodedToken = this.decodeToken(token);
  return decodedToken ? decodedToken[claimKey] : null;
}

 

Using the JWT service in components

With the JWT service in place, we can now use it in our Angular components to extract claim values. In this example, we’ll use the AppComponent to demonstrate how to use the JwtService. Update the app.component.ts file with the following code:

import { Component } from '@angular/core';
import { JwtService } from './jwt.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
            title = 'jwt-angular-demo';

              constructor(private jwtService: JwtService) {
                    const token = 'your_jwt_token_here';
                    const userEmail = this.jwtService.getClaim(token, 'email');
                    console.log('User Email:', userEmail);
               }
}

Replace `‘your_jwt_token_here’` with an actual JWT string.

 

Example: Retrieving user information from JWT

Assume that we have a JWT containing the following payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "email": "[email protected]",
  "iat": 1516239022
}

We can use the JwtService to extract the user’s email address as shown in the AppComponent example above. The console will output:

User Email: [email protected]

 

Conclusion

In this article, we demonstrated how to set up an Angular project, add the necessary libraries, and create a service to handle JWT operations such as extracting claim values from a JWT string. This approach enables developers to quickly and easily retrieve relevant information from JWT tokens, which can be useful in various scenarios, such as displaying user-specific data in the application or making authorization decisions based on claims.

Leave a Comment

Your email address will not be published. Required fields are marked *