fix(http): enable xsrf for root-provided HttpClient

Include the XSRF interceptor in the root token factory so the automatically provided HttpClient retains the documented default protection without requiring provideHttpClient().
This commit is contained in:
Jaime Burgos
2026-07-29 10:40:09 -05:00
committed by GitHub
parent d5e8b1ef7a
commit de240a5d0e
3 changed files with 18 additions and 4 deletions
+2 -1
View File
@@ -20,6 +20,7 @@ import type {HttpHandler} from './backend';
import {HttpRequest} from './request';
import {HttpEvent} from './response';
import {xsrfInterceptorFn} from './xsrf';
/**
* Intercepts and handles an `HttpRequest` or `HttpResponse`.
@@ -200,7 +201,7 @@ export const HTTP_INTERCEPTORS = new InjectionToken<readonly HttpInterceptor[]>(
*/
export const HTTP_INTERCEPTOR_FNS = new InjectionToken<readonly HttpInterceptorFn[]>(
typeof ngDevMode !== 'undefined' && ngDevMode ? 'HTTP_INTERCEPTOR_FNS' : '',
{factory: () => []},
{factory: () => [xsrfInterceptorFn]},
);
/**
+2 -2
View File
@@ -17,8 +17,8 @@ import {
import {Observable} from 'rxjs';
import {DOCUMENT, ɵparseCookieValue as parseCookieValue, PlatformLocation} from '../../index';
import {HttpHandler} from './backend';
import {HttpHandlerFn, HttpInterceptor} from './interceptor';
import type {HttpHandler} from './backend';
import type {HttpHandlerFn, HttpInterceptor} from './interceptor';
import {HttpRequest} from './request';
import {HttpEvent} from './response';
+14 -1
View File
@@ -267,6 +267,19 @@ describe('provideHttpClient', () => {
});
describe('xsrf protection', () => {
it('should enable xsrf protection for the root-provided HttpClient', () => {
TestBed.configureTestingModule({
providers: [provideHttpClientTesting(), {provide: PLATFORM_ID, useValue: 'test'}],
});
setXsrfToken('abcdefg');
TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-XSRF-TOKEN')).toEqual('abcdefg');
req.flush('');
});
it('should enable xsrf protection by default', () => {
TestBed.configureTestingModule({
providers: [
@@ -317,7 +330,7 @@ describe('provideHttpClient', () => {
TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.has('X-Custom-Xsrf-Header')).toBeFalse();
expect(req.request.headers.has('X-XSRF-TOKEN')).toBeFalse();
req.flush('');
});