Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit f5e4abc

Browse files
committed
feat($http): support sending XSRF token to whitelisted origins
Normally, the XSRF token will not be set for cross-origin requests. With this commit, it is possible to whitelist additional origins, so that requests to these origins will include the XSRF token header. Fixes #7862
1 parent 98e0e04 commit f5e4abc

File tree

6 files changed

+373
-116
lines changed

6 files changed

+373
-116
lines changed

src/.eslintrc.json

+1
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@
161161
"urlResolve": false,
162162
"urlIsSameOrigin": false,
163163
"urlIsSameOriginAsBaseUrl": false,
164+
"urlIsAllowedOriginChecker": false,
164165

165166
/* ng/controller.js */
166167
"identifierForController": false,

src/ng/http.js

+79-17
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ function $HttpParamSerializerProvider() {
3434
* * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
3535
*
3636
* Note that serializer will sort the request parameters alphabetically.
37-
* */
37+
*/
3838

3939
this.$get = function() {
4040
return function ngParamSerializer(params) {
@@ -101,7 +101,7 @@ function $HttpParamSerializerJQLikeProvider() {
101101
* });
102102
* ```
103103
*
104-
* */
104+
*/
105105
this.$get = function() {
106106
return function jQueryLikeParamSerializer(params) {
107107
if (!params) return '';
@@ -261,7 +261,7 @@ function isSuccess(status) {
261261
*
262262
* @description
263263
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
264-
* */
264+
*/
265265
function $HttpProvider() {
266266
/**
267267
* @ngdoc property
@@ -315,7 +315,7 @@ function $HttpProvider() {
315315
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
316316
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
317317
*
318-
**/
318+
*/
319319
var defaults = this.defaults = {
320320
// transform incoming response data
321321
transformResponse: [defaultHttpResponseTransform],
@@ -362,7 +362,7 @@ function $HttpProvider() {
362362
*
363363
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
364364
* otherwise, returns the current configured value.
365-
**/
365+
*/
366366
this.useApplyAsync = function(value) {
367367
if (isDefined(value)) {
368368
useApplyAsync = !!value;
@@ -383,9 +383,49 @@ function $HttpProvider() {
383383
* array, on request, but reverse order, on response.
384384
*
385385
* {@link ng.$http#interceptors Interceptors detailed info}
386-
**/
386+
*/
387387
var interceptorFactories = this.interceptors = [];
388388

389+
/**
390+
* @ngdoc property
391+
* @name $httpProvider#xsrfWhitelistedOrigins
392+
* @description
393+
*
394+
* Array containing URLs whose origins are considered trusted enough to receive the XSRF token.
395+
* See the {@link ng.$http#security-considerations Security Considerations} sections for more
396+
* details on XSRF.
397+
*
398+
* **Note:** An "origin" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme),
399+
* the [hostname](https://en.wikipedia.org/wiki/Hostname) and the
400+
* [port number](https://en.wikipedia.org/wiki/Port_(computer_networking).
401+
*
402+
* <div class="alert alert-warning">
403+
* It is not possible to whitelist specific URLs/paths. The `path`, `query` and `fragment` parts
404+
* of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be
405+
* treated as `https://foo.com/`, meaning that **all** requests to URLs starting with
406+
* `https://foo.com/` will include the XSRF token.
407+
* </div>
408+
*
409+
* ## Example
410+
*
411+
* ```
412+
* // App served from `https://example.com`
413+
* angular.
414+
* module('xsrfWhitelistedOriginsExample', []).
415+
* config(['$httpProvider', function($httpProvider) {
416+
* $httpProvider.xsrfWhitelistedOrigins.push('https://api.example.com/');
417+
* }]).
418+
* run(['$http', function($http) {
419+
* // The XSRF token will be sent
420+
* $http.get('https://api.example.com/preferences').then(...);
421+
*
422+
* // The XSRF token will NOT be sent
423+
* $http.get('https://stats.example.com/activity').then(...);
424+
* }]);
425+
* ```
426+
*/
427+
var xsrfWhitelistedOrigins = this.xsrfWhitelistedOrigins = [];
428+
389429
this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
390430
function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
391431

@@ -409,6 +449,11 @@ function $HttpProvider() {
409449
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
410450
});
411451

452+
/**
453+
* A function to check request URLs against a list of allowed origins.
454+
*/
455+
var urlIsAllowedOrigin = urlIsAllowedOriginChecker(xsrfWhitelistedOrigins);
456+
412457
/**
413458
* @ngdoc service
414459
* @kind function
@@ -765,25 +810,42 @@ function $HttpProvider() {
765810
* which the attacker can trick an authenticated user into unknowingly executing actions on your
766811
* website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the
767812
* $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
768-
* header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
769-
* cookie, your server can be assured that the XHR came from JavaScript running on your domain.
770-
* The header will not be set for cross-domain requests.
813+
* header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read
814+
* the cookie, your server can be assured that the XHR came from JavaScript running on your
815+
* domain.
771816
*
772817
* To take advantage of this, your server needs to set a token in a JavaScript readable session
773818
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
774-
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
775-
* that only JavaScript running on your domain could have sent the request. The token must be
776-
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
819+
* server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be
820+
* sure that only JavaScript running on your domain could have sent the request. The token must
821+
* be unique for each user and must be verifiable by the server (to prevent the JavaScript from
777822
* making up its own tokens). We recommend that the token is a digest of your site's
778823
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
779824
* for added security.
780825
*
781-
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
782-
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
783-
* or the per-request config object.
826+
* The header will &mdash; by default &mdash; **not** be set for cross-domain requests. This
827+
* prevents unauthorized servers (e.g. malicious or compromized 3rd-party APIs) from gaining
828+
* access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you
829+
* want to, you can whitelist additional origins to also receive the XSRF token, by adding them
830+
* to {@link ng.$httpProvider#xsrfWhitelistedOrigins xsrfWhitelistedOrigins}. This might be
831+
* useful, for example, if your application, served from `example.com`, needs to access your API
832+
* at `api.example.com`.
833+
* See {@link ng.$httpProvider#xsrfWhitelistedOrigins $httpProvider.xsrfWhitelistedOrigins} for
834+
* more details.
835+
*
836+
* <div class="alert alert-danger">
837+
* **Warning**<br />
838+
* Only whitelist origins that you have control over and make sure you understand the
839+
* implications of doing so.
840+
* </div>
841+
*
842+
* The name of the cookie and the header can be specified using the `xsrfCookieName` and
843+
* `xsrHeaderName` properties of either `$httpProvider.defaults` at config-time,
844+
* `$http.defaults` at run-time, or the per-request config object.
784845
*
785846
* In order to prevent collisions in environments where multiple AngularJS apps share the
786-
* same domain or subdomain, we recommend that each application uses unique cookie name.
847+
* same domain or subdomain, we recommend that each application uses a unique cookie name.
848+
*
787849
*
788850
* @param {object} config Object describing the request to be made and how it should be
789851
* processed. The object has following properties:
@@ -1343,7 +1405,7 @@ function $HttpProvider() {
13431405
// if we won't have the response in cache, set the xsrf headers and
13441406
// send the request to the backend
13451407
if (isUndefined(cachedResp)) {
1346-
var xsrfValue = urlIsSameOrigin(config.url)
1408+
var xsrfValue = urlIsAllowedOrigin(config.url)
13471409
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
13481410
: undefined;
13491411
if (xsrfValue) {

src/ng/urlUtils.js

+41-11
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ function urlResolve(url) {
8484
}
8585

8686
/**
87-
* Parse a request URL and determine whether this is a same-origin request as the application document.
87+
* Parse a request URL and determine whether this is a same-origin request as the application
88+
* document.
8889
*
8990
* @param {string|object} requestUrl The url of the request as a string that will be resolved
9091
* or a parsed URL object.
@@ -109,37 +110,66 @@ function urlIsSameOriginAsBaseUrl(requestUrl) {
109110
}
110111

111112
/**
112-
* Determines if two URLs share the same origin.
113+
* Create a function that can check a URL's origin against a list of allowed/whitelisted origins.
114+
* The current location's origin is implicitly trusted.
113115
*
114-
* @param {string|object} url1 First URL to compare as a string or a normalized URL in the form of
115-
* a dictionary object returned by `urlResolve()`.
116-
* @param {string|object} url2 Second URL to compare as a string or a normalized URL in the form of
116+
* @param {string[]} whitelistedOriginUrls - A list of URLs (strings), whose origins are trusted.
117+
*
118+
* @returns {Function} - A function that receives a URL (string or parsed URL object) and returns
119+
* whether it is of an allowed origin.
120+
*/
121+
function urlIsAllowedOriginChecker(whitelistedOriginUrls) {
122+
var parsedAllowedOriginUrls = [originUrl].concat(whitelistedOriginUrls.map(urlResolve));
123+
124+
/**
125+
* Check whether the specified URL (string or parsed URL object) has an origin that is allowed
126+
* based on a list of whitelisted-origin URLs. The current location's origin is implicitly
127+
* trusted.
128+
*
129+
* @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be
130+
* resolved or a parsed URL object).
131+
*
132+
* @returns {boolean} - Whether the specified URL is of an allowed origin.
133+
*/
134+
return function urlIsAllowedOrigin(requestUrl) {
135+
var parsedUrl = isString(requestUrl) ? urlResolve(requestUrl) : requestUrl;
136+
return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl));
137+
};
138+
}
139+
140+
/**
141+
* Determine if two URLs share the same origin.
142+
*
143+
* @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of
117144
* a dictionary object returned by `urlResolve()`.
118-
* @return {boolean} True if both URLs have the same origin, and false otherwise.
145+
* @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form
146+
* of a dictionary object returned by `urlResolve()`.
147+
*
148+
* @returns {boolean} - True if both URLs have the same origin, and false otherwise.
119149
*/
120150
function urlsAreSameOrigin(url1, url2) {
121-
url1 = (isString(url1)) ? urlResolve(url1) : url1;
122-
url2 = (isString(url2)) ? urlResolve(url2) : url2;
151+
url1 = isString(url1) ? urlResolve(url1) : url1;
152+
url2 = isString(url2) ? urlResolve(url2) : url2;
123153

124154
return (url1.protocol === url2.protocol &&
125155
url1.host === url2.host);
126156
}
127157

128158
/**
129159
* Returns the current document base URL.
130-
* @return {string}
160+
* @returns {string}
131161
*/
132162
function getBaseUrl() {
133163
if (window.document.baseURI) {
134164
return window.document.baseURI;
135165
}
136166

137-
// document.baseURI is available everywhere except IE
167+
// `document.baseURI` is available everywhere except IE
138168
if (!baseUrlParsingNode) {
139169
baseUrlParsingNode = window.document.createElement('a');
140170
baseUrlParsingNode.href = '.';
141171

142-
// Work-around for IE bug described in Implementation Notes. The fix in urlResolve() is not
172+
// Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not
143173
// suitable here because we need to track changes to the base URL.
144174
baseUrlParsingNode = baseUrlParsingNode.cloneNode(false);
145175
}

test/.eslintrc.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,8 @@
152152
/* urlUtils.js */
153153
"urlResolve": false,
154154
"urlIsSameOrigin": false,
155-
"urlIsSameOriginAsBaseUrl": true,
155+
"urlIsSameOriginAsBaseUrl": false,
156+
"urlIsAllowedOriginChecker": false,
156157

157158
/* karma */
158159
"dump": false,

0 commit comments

Comments
 (0)