Skip to content

Instantly share code, notes, and snippets.

@anddam
Last active July 12, 2024 11:07
Show Gist options
  • Save anddam/f54c595f63a9371cd41a930418a91d47 to your computer and use it in GitHub Desktop.
Save anddam/f54c595f63a9371cd41a930418a91d47 to your computer and use it in GitHub Desktop.
Angular HttpClientXsrfModule example
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpXsrfTokenExtractor } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class HttpXSRFInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'X-CSRFTOKEN';
const respHeaderName = 'X-CUSTOM-CSRFTOKEN';
let token = this.tokenExtractor.getToken() as string;
console.log('token:', token);
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(respHeaderName, token) });
}
return next.handle(req);
}
}
@DbrmnPhrh
Copy link

Many Thanks! You save my life )))

@anddam
Copy link
Author

anddam commented Apr 11, 2024

Just me saving the world, one CSRF token at time. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment