feat(common): on-by-default XSRF support in HttpClient (#18108)

Fixes #18100
This commit is contained in:
Alex Rickabaugh
2017-07-13 17:22:02 -07:00
committed by Igor Minar
parent 3d85f72652
commit dd04f09483
11 changed files with 328 additions and 31 deletions

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {InjectionToken} from '@angular/core';
import {Injectable, InjectionToken} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpHandler} from './backend';
@ -64,3 +64,10 @@ export class HttpInterceptorHandler implements HttpHandler {
* @experimental
*/
export const HTTP_INTERCEPTORS = new InjectionToken<HttpInterceptor[]>('HTTP_INTERCEPTORS');
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}

View File

@ -6,13 +6,15 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, NgModule, Optional} from '@angular/core';
import {Inject, ModuleWithProviders, NgModule, Optional, forwardRef} from '@angular/core';
import {HttpBackend, HttpHandler} from './backend';
import {HttpClient} from './client';
import {HTTP_INTERCEPTORS, HttpInterceptor, HttpInterceptorHandler} from './interceptor';
import {HTTP_INTERCEPTORS, HttpInterceptor, HttpInterceptorHandler, NoopInterceptor} from './interceptor';
import {JsonpCallbackContext, JsonpClientBackend, JsonpInterceptor} from './jsonp';
import {BrowserXhr, HttpXhrBackend, XhrFactory} from './xhr';
import {HttpXsrfCookieExtractor, HttpXsrfInterceptor, HttpXsrfTokenExtractor, XSRF_COOKIE_NAME, XSRF_HEADER_NAME} from './xsrf';
/**
@ -47,6 +49,58 @@ export function jsonpCallbackContext(): Object {
return {};
}
/**
* `NgModule` which adds XSRF protection support to outgoing requests.
*
* Provided the server supports a cookie-based XSRF protection system, this
* module can be used directly to configure XSRF protection with the correct
* cookie and header names.
*
* If no such names are provided, the default is to use `X-XSRF-TOKEN` for
* the header name and `XSRF-TOKEN` for the cookie name.
*
* @experimental
*/
@NgModule({
providers: [
HttpXsrfInterceptor,
{provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true},
{provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor},
{provide: XSRF_COOKIE_NAME, useValue: 'XSRF-TOKEN'},
{provide: XSRF_HEADER_NAME, useValue: 'X-XSRF-TOKEN'},
],
})
export class HttpXsrfModule {
/**
* Disable the default XSRF protection.
*/
static disable(): ModuleWithProviders {
return {
ngModule: HttpXsrfModule,
providers: [
{provide: HttpXsrfInterceptor, useClass: NoopInterceptor},
],
};
}
/**
* Configure XSRF protection to use the given cookie name or header name,
* or the default names (as described above) if not provided.
*/
static withOptions(options: {
cookieName?: string,
headerName?: string,
} = {}): ModuleWithProviders {
return {
ngModule: HttpXsrfModule,
providers: [
options.cookieName ? {provide: XSRF_COOKIE_NAME, useValue: options.cookieName} : [],
options.headerName ? {provide: XSRF_HEADER_NAME, useValue: options.headerName} : [],
],
};
}
}
/**
* `NgModule` which provides the `HttpClient` and associated services.
*
@ -56,6 +110,12 @@ export function jsonpCallbackContext(): Object {
* @experimental
*/
@NgModule({
imports: [
HttpXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
}),
],
providers: [
HttpClient,
// HttpHandler is the backend + interceptors and is constructed
@ -90,4 +150,4 @@ export class HttpClientModule {
],
})
export class HttpClientJsonpModule {
}
}

View File

@ -0,0 +1,93 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DOCUMENT, ɵparseCookieValue as parseCookieValue} from '@angular/common';
import {Inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpHandler} from './backend';
import {HttpInterceptor} from './interceptor';
import {HttpRequest} from './request';
import {HttpEvent} from './response';
export const XSRF_COOKIE_NAME = new InjectionToken<string>('XSRF_COOKIE_NAME');
export const XSRF_HEADER_NAME = new InjectionToken<string>('XSRF_HEADER_NAME');
/**
* Retrieves the current XSRF token to use with the next outgoing request.
*
* @experimental
*/
export abstract class HttpXsrfTokenExtractor {
/**
* Get the XSRF token to use with an outgoing request.
*
* Will be called for every request, so the token may change between requests.
*/
abstract getToken(): string|null;
}
/**
* `HttpXsrfTokenExtractor` which retrieves the token from a cookie.
*/
@Injectable()
export class HttpXsrfCookieExtractor implements HttpXsrfTokenExtractor {
private lastCookieString: string = '';
private lastToken: string|null = null;
/**
* @internal for testing
*/
parseCount: number = 0;
constructor(
@Inject(DOCUMENT) private doc: any, @Inject(PLATFORM_ID) private platform: string,
@Inject(XSRF_COOKIE_NAME) private cookieName: string) {}
getToken(): string|null {
if (this.platform === 'server') {
return null;
}
const cookieString = this.doc.cookie || '';
if (cookieString !== this.lastCookieString) {
this.parseCount++;
this.lastToken = parseCookieValue(cookieString, this.cookieName);
this.lastCookieString = cookieString;
}
return this.lastToken;
}
}
/**
* `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) {}
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 (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);
}
}