Blog>
Snippets

Using Angular HttpInterceptor for JWT Authentication

Implement an HttpInterceptor to automatically attach JWT tokens to HTTP requests for secure API calls.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Add authorization header with jwt token if available
        const currentUser = this.authService.currentUserValue;
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: { 
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
}
This code defines a JWT interceptor service that implements HttpInterceptor. It injects the AuthService to get the current user's token. In the intercept method, it inspects outgoing HTTP requests, and if the user is currently logged in and has a token, it clones the request to add an Authorization header with the JWT token. Then, it forwards the modified request to the next handler.
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';

// ... within your module providers

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    // ... other providers
]
This snippet shows how to register the JwtInterceptor within an Angular module. It adds the interceptor to the HTTP_INTERCEPTORS multi-provider token, indicating that this interceptor should be used for all outgoing HTTP requests.
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

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

    constructor() {
        this.currentUserSubject = new BehaviorSubject<any>(JSON.parse(localStorage.getItem('currentUser')));
        this.currentUser = this.currentUserSubject.asObservable();
    }

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

    // Other authentication related methods
}
This is a representation of an AuthService, which holds the current user's data, including their JWT token. The service uses a BehaviorSubject to track the current user's state and provides a getter to access the current user's value synchronously. The interceptor would use this service to get the currently authenticated user's JWT token.