Last active
July 12, 2024 11:07
-
-
Save anddam/f54c595f63a9371cd41a930418a91d47 to your computer and use it in GitHub Desktop.
Angular HttpClientXsrfModule example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
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
Many Thanks! You save my life )))