Using HttpXsrfTokenExtractor in Angular Interceptor
Create an HTTP interceptor that uses HttpXsrfTokenExtractor to add a CSRF token to outgoing requests.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpXsrfTokenExtractor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class CsrfInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(headerName, token) });
}
return next.handle(req);
}
}
This code creates an Injectable Angular HTTP Interceptor 'CsrfInterceptor' class that utilizes the 'HttpXsrfTokenExtractor' service to extract the CRSF token from cookies. The interceptor intercepts all outgoing HTTP requests and checks if the request headers already have the CSRF token header ('X-XSRF-TOKEN'). If not, it clones the request object and adds the header with the extracted token. It then forwards the modified request to the next handler in the chain.