Token Interceptor Service

While we could pass write code to add the Authorization header to our HTTP client requests in our API service, we would quickly start violating the DRY principle of programming. An Angular HTTP interceptor The final piece of our Authentication module is a service that provides an [HTTP interceptor] will attach the authenticated user's JWT access token to every API request. Let's see what that code looks like:

// src/app/auth/secure-interceptor.service.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth.service';
import { Observable, throwError } from 'rxjs';
import { filter, mergeMap, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SecureInterceptor implements HttpInterceptor {

  constructor(private auth: AuthService) { }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    if (req.url.indexOf('/secure/') > -1) {
      return this.auth.accessToken$.pipe(
        filter(token => typeof token === 'string'),
        mergeMap(token => {
          const tokenReq = req.clone({
            setHeaders: { Authorization: `Bearer ${token}` }
          });
          return next.handle(tokenReq);
        }),
        catchError(err => throwError(err))
      );
    }
    return next.handle(req);
  }
}

This service intercepts each outgoing HTTP request. It clones the request and adds an Authorization: Bearer {jwt} header using the authenticated user's access token.

results matching ""

    No results matching ""