Add an authorization token (JWT) to outgoing HTTP requests
Add an authorization token (JWT) to outgoing HTTP requests:
The AuthInterceptor adds the JWT token to the Authorization header of all outgoing HTTP requests, but only if the token is available and not expired.
Coding:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private jwtHelper: JwtHelperService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('access_token');
if (token && !this.jwtHelper.isTokenExpired(token)) {
const cloned = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
return next.handle(cloned);
}
return next.handle(req);
}
}
Explanation:
HttpRequest: Represents an HTTP request made from the client, containing details like URL, headers, body, and method type (e.g., GET, POST).
HttpEvent: A generic type that represents various events in the lifecycle of an HTTP request and response. It can be used to handle different stages of the request/response process, such as request sent, response received, or errors.
JwtHelperService
from @auth0/angular-jwt
is used to check if the JWT token is expired.
Comments
Post a Comment