Skip to content

Commit

Permalink
refactor(http): convert the XSRF interceptor to functional style (#47502
Browse files Browse the repository at this point in the history
)

This commit converts the XSRF interceptor into a functional interceptor
instead of a legacy class-based interceptor.

PR Close #47502
  • Loading branch information
alxhub authored and thePunderWoman committed Oct 6, 2022
1 parent ab6a3d7 commit 67ef8b1
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 28 deletions.
52 changes: 29 additions & 23 deletions packages/common/http/src/xsrf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
*/

import {DOCUMENT, ɵparseCookieValue as parseCookieValue} from '@angular/common';
import {Inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core';
import {EnvironmentInjector, Inject, inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core';
import {Observable} from 'rxjs';

import {HttpHandler} from './backend';
import {HttpInterceptor} from './interceptor';
import {HttpHandlerFn, HttpInterceptor} from './interceptor';
import {HttpRequest} from './request';
import {HttpEvent} from './response';

Expand Down Expand Up @@ -74,32 +74,38 @@ export class HttpXsrfCookieExtractor implements HttpXsrfTokenExtractor {
}
}

export function xsrfInterceptorFn(
req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
const lcUrl = req.url.toLowerCase();
// Skip both non-mutating requests and absolute URLs.
// Non-mutating requests don't require a token, and absolute URLs require special handling
// anyway as the cookie set
// on our origin is not the same as the token expected by another origin.
if (!inject(XSRF_ENABLED) || req.method === 'GET' || req.method === 'HEAD' ||
lcUrl.startsWith('http://') || lcUrl.startsWith('https://')) {
return next(req);
}

const token = inject(HttpXsrfTokenExtractor).getToken();
const headerName = inject(XSRF_HEADER_NAME);

// Be careful not to overwrite an existing header of the same name.
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({headers: req.headers.set(headerName, token)});
}
return next(req);
}

/**
* `HttpInterceptor` which adds an XSRF token to eligible outgoing requests.
*/
@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {
constructor(
private tokenService: HttpXsrfTokenExtractor,
@Inject(XSRF_HEADER_NAME) private headerName: string,
@Inject(XSRF_ENABLED) private enabled: boolean) {}
constructor(private injector: EnvironmentInjector) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const lcUrl = req.url.toLowerCase();
// Skip both non-mutating requests and absolute URLs.
// Non-mutating requests don't require a token, and absolute URLs require special handling
// anyway as the cookie set
// on our origin is not the same as the token expected by another origin.
if (!this.enabled || req.method === 'GET' || req.method === 'HEAD' ||
lcUrl.startsWith('http://') || lcUrl.startsWith('https://')) {
return next.handle(req);
}
const token = this.tokenService.getToken();

// Be careful not to overwrite an existing header of the same name.
if (token !== null && !req.headers.has(this.headerName)) {
req = req.clone({headers: req.headers.set(this.headerName, token)});
}
return next.handle(req);
intercept(initialRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.injector.runInContext(
() =>
xsrfInterceptorFn(initialRequest, downstreamRequest => next.handle(downstreamRequest)));
}
}
45 changes: 40 additions & 5 deletions packages/common/http/test/xsrf_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@

import {HttpHeaders} from '@angular/common/http/src/headers';
import {HttpRequest} from '@angular/common/http/src/request';
import {HttpXsrfCookieExtractor, HttpXsrfInterceptor, HttpXsrfTokenExtractor} from '@angular/common/http/src/xsrf';
import {HttpXsrfCookieExtractor, HttpXsrfInterceptor, HttpXsrfTokenExtractor, XSRF_ENABLED, XSRF_HEADER_NAME} from '@angular/common/http/src/xsrf';
import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend';
import {TestBed} from '@angular/core/testing';

class SampleTokenExtractor extends HttpXsrfTokenExtractor {
constructor(private token: string|null) {
Expand All @@ -24,9 +25,26 @@ class SampleTokenExtractor extends HttpXsrfTokenExtractor {
{
describe('HttpXsrfInterceptor', () => {
let backend: HttpClientTestingBackend;
const interceptor = new HttpXsrfInterceptor(
new SampleTokenExtractor('test'), 'X-XSRF-TOKEN', /* enabled */ true);
let interceptor: HttpXsrfInterceptor;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: HttpXsrfTokenExtractor,
useValue: new SampleTokenExtractor('test'),
},
{
provide: XSRF_HEADER_NAME,
useValue: 'X-XSRF-TOKEN',
},
{
provide: XSRF_ENABLED,
useValue: true,
},
HttpXsrfInterceptor,
],
});
interceptor = TestBed.inject(HttpXsrfInterceptor);
backend = new HttpClientTestingBackend();
});
it('applies XSRF protection to outgoing requests', () => {
Expand Down Expand Up @@ -59,8 +77,25 @@ class SampleTokenExtractor extends HttpXsrfTokenExtractor {
req.flush({});
});
it('does not set the header for a null token', () => {
const interceptor = new HttpXsrfInterceptor(
new SampleTokenExtractor(null), 'X-XSRF-TOKEN', /* enabled */ true);
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
{
provide: HttpXsrfTokenExtractor,
useValue: new SampleTokenExtractor(null),
},
{
provide: XSRF_HEADER_NAME,
useValue: 'X-XSRF-TOKEN',
},
{
provide: XSRF_ENABLED,
useValue: true,
},
HttpXsrfInterceptor,
],
});
interceptor = TestBed.inject(HttpXsrfInterceptor);
interceptor.intercept(new HttpRequest('POST', '/test', {}), backend).subscribe();
const req = backend.expectOne('/test');
expect(req.request.headers.has('X-XSRF-TOKEN')).toEqual(false);
Expand Down

0 comments on commit 67ef8b1

Please sign in to comment.