All files / app/interceptors/xsrf xsrf.interceptor.ts

100% Statements 6/6
100% Branches 2/2
100% Functions 1/1
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                                          1x           13x                                   11x 11x 11x       11x      
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpXsrfTokenExtractor,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
 
/**
 * Http interceptor adding the XSRF token to every request to the API.
 *
 * The set up was done using :
 * https://www.stackhawk.com/blog/angular-csrf-protection-guide-examples-and-how-to-enable-it/
 * The cookie name can be configured by specifying the value in app.module
 * exports. The default value is XSRF-TOKEN.
 *
 * And to learn more about csrf : https://www.baeldung.com/spring-security-csrf
 */
@Injectable()
export class XsrfInterceptor implements HttpInterceptor {
  /**
   * The xsrf interceptor constructor
   *
   * @param tokenExtractor The {@link HttpXsrfTokenExtractor}
   */
  constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}
 
  /**
   * Intercept any request. Uses the `HttpXsrfTokenExtractor` to get the token
   * in the cookies, and sets up the xsrf token in the header of the request.
   * The header name is X-XSRF-TOKEN but can be configured here. To configure
   * the cookie name, the HttpClientXsrfModule has to be configured.
   *
   * @param req The intercepted request
   * @param next The `HttpHandler`
   * @returns The request, having added the xsrf header.
   */
  intercept(
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    req: HttpRequest<any>,
    next: HttpHandler
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
  ): Observable<HttpEvent<any>> {
    const cookieheaderName = 'X-XSRF-TOKEN';
    const csrfToken = this.tokenExtractor.getToken() as string;
    req = req.clone({
      headers: req.headers.set(cookieheaderName, csrfToken ?? 'null'),
      withCredentials: true,
    });
    return next.handle(req);
  }
}