Refreshing CSRF Tokens after Each Request in Angular
Provide a code snippet for an Angular service that refreshes the CSRF token after each successful HTTP request.
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CsrfService {
private csrfToken: string | null = null;
constructor(private http: HttpClient) {}
// Call this method to refresh CSRF token
public refreshCsrfToken(): void {
this.http.get('/api/csrf-token') // Replace with your endpoint
.pipe(
tap((response: any) => {
// Handle the response and set the csrfToken with the new value
this.csrfToken = response.csrfToken;
// Update default headers with the new CSRF token
this.http.options = {
headers: new HttpHeaders({
'X-CSRF-TOKEN': this.csrfToken
})
};
})
).subscribe();
}
// Use this method to make HTTP request with updated CSRF token
public makeRequest(): void {
// Example request
this.http.get('/api/protected-endpoint')
.pipe(
tap(() => this.refreshCsrfToken()) // Refresh CSRF token after each successful request
).subscribe();
}
}
This Angular service contains a method to refresh the CSRF token after each successful HTTP request. 'refreshCsrfToken' fetches the new token and updates the HttpClient headers, while 'makeRequest' is an example of how to use the service to make a request and then refresh the token.