JWT Authentication in Angular 11 – Token based Authentication tutorial with example

In this post, we will understand what is JWT authentication, and finally, we are going to see how to implement authentication, manage tokens, and pass tokens to servers from Angular with example.

JSON Web Token (JWT) are digitally signed JSON payloads and token-based stateless authentication mechanisms.

A JWT consists of three parts that are: The Header, Payload, and Signature. Both the header and the payload store data in the JSON format, which is Base64-encoded, while The signature is created using the Base 64 encoding of the header and the payload.

JWT is usually used in HTTP Authorization headers and temporary replacement for the username/password combination!

Structure of a JWT

A well-formed JWT consists consist of three parts separated by dots (.), which are:

structure of a JWT Authentication

Here is a JWT example

JWT Authentication in Angular

Header
The header typically consists of two parts:
1. Typ – the type of the token, which is JWT.
2. Alg – the signing algorithm being used, such as HMAC SHA256 or RSA.
Payload
The second part of the JWT is the payload, which contains statements about the entity (typically, the user) and additional entity attributes, which are called claims.
Signature
The Signature is the last part after the second dot(.). This is responsible for validating the JWT.

How JWT Authentication Work

A browser or mobile client makes a request to the authentication server containing user login information. The authentication server generates a new JWT access token and returns it to the client. On every request to a restricted resource, the client sends the access token in the query string or Authorization header. The server then validates the token and, if it’s valid, returns the secure resource to the client.

jwt authentication

How to implement JWT Authentication in Angular

  • Create a new angular project with the ng new command. For more info about the Angular CLI see https://angular.io/cli.
  • Start the application by running ng serve from the command, this will build the application and automatically launch it in the browser on the URL http://localhost:4200.
  • Create an auth guard that’s used to prevent unauthenticated users from accessing restricted routes and implement the CanActivate interface which allows the guard to decide if a route can be activated with the canActivate() method.
import { Injectable } from '@angular/core';
import {  HttpRequest,  HttpHandler,  HttpEvent,  HttpInterceptor,} from'@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from './AuthenticationService';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available( logged in user)
    let currentUser = this.authenticationService.currentUserValue;
    if (currentUser && currentUser.token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentUser.token}`,
        },
      });
    }
    return next.handle(request);
  }
}
 

The authentication service is used to login & logout of the Angular app.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../models/userModel';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
  private currentUserSubject: BehaviorSubject<User>;
  public currentUser: Observable<User>;

  constructor(private http: HttpClient) {
    this.currentUserSubject = new BehaviorSubject<User>(
      JSON.parse(localStorage.getItem('currentUser'))
    );
    this.currentUser = this.currentUserSubject.asObservable();
  }

  public get currentUserValue(): User {
    return this.currentUserSubject.value;
  }

  login(username: string, password: string) {
    return this.http
      .post<any>(`/users/authenticate`, { username, password })
      .pipe(
        map((user) => {
          localStorage.setItem('currentUser', JSON.stringify(user));
          this.currentUserSubject.next(user);
          return user;
        })
      );
  }

  logout() {
    localStorage.removeItem('currentUser');
    this.currentUserSubject.next(null);
  }
}
 
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './services/JwtInterceptor';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, 
],
})
export class AppModule { }
 

Related Post

Source code available for download

The source code is available on Stackblitz of the  JWT Authentication in Angular 11 – Token based Authentication tutorial with example

Demo Application URL : URL or  https://stackblitz.com/edit/implement-jwt-authentication-in-angular?file=src/app/app.component.ts 

  • Post category:Angular
  • Reading time:5 mins read