mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
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:
@@ -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]},
|
||||
);
|
||||
|
||||
/**
|
||||
|
||||
@@ -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';
|
||||
|
||||
|
||||
@@ -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('');
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user