Skip to main content

Angular Login App with JWT token authentication | Interceptor | Angular Login

A JWT (JSON Web Token) in Angular is a compact, URL-safe token used to securely transmit information between parties as a JSON object. It is typically used for user authentication and authorization in Angular applications.



 How JWT  token Works in Angular

User Login:
The user logs in with credentials (e.g., username and password).
The server verifies the credentials and responds with a JWT if authentication is successful.

Store Token:

The Angular application stores the token (e.g., in localStorage or sessionStorage).

onSubmit(){
  this.service.loginUser(this.loginObj).subscribe((res:any)=>{
    if(res.result){
      alert("Login Sucessfully");
      localStorage.setItem("loginToken",res.data.token);
      this.route.navigateByUrl('/dashboard')

    }else{
      alert(res.message)
    }
  })
}

Attach Token to Requests:

An HTTP interceptor in Angular appends the JWT to outgoing requests as an Authorization header:

import { HttpInterceptorFn } from '@angular/common/http';

export const customInterceptor: HttpInterceptorFn = (req, next) => {
  debugger;
 
  const token = localStorage.getItem("loginToken");
  const newReq = req.clone({
    setHeaders:{
      Authorization: `Bearer ${token}`
    }
  })
  return next(newReq);
};

Server Verifies Token:

The server validates the token and grants or denies access based on its validity and claims.

More details GithubRepo

Comments

© 2020 The JavaDS Hub

Designed by Open Themes & Nahuatl.mx.