Skip to content

Commit 0455b09

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 angular#7862
1 parent a82a8a5 commit 0455b09

File tree

6 files changed

+373
-105
lines changed

6 files changed

+373
-105
lines changed

src/.jshintrc

+1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@
156156
/* urlUtils.js */
157157
"urlResolve": false,
158158
"urlIsSameOrigin": false,
159+
"urlIsAllowedOriginChecker": false,
159160

160161
/* ng/controller.js */
161162
"identifierForController": false,

src/ng/http.js

+80-18
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ function $HttpParamSerializerProvider() {
3838
* * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
3939
*
4040
* Note that serializer will sort the request parameters alphabetically.
41-
* */
41+
*/
4242

4343
this.$get = function() {
4444
return function ngParamSerializer(params) {
@@ -103,7 +103,7 @@ function $HttpParamSerializerJQLikeProvider() {
103103
* });
104104
* ```
105105
*
106-
* */
106+
*/
107107
this.$get = function() {
108108
return function jQueryLikeParamSerializer(params) {
109109
if (!params) return '';
@@ -248,7 +248,7 @@ function isSuccess(status) {
248248
* @name $httpProvider
249249
* @description
250250
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
251-
* */
251+
*/
252252
function $HttpProvider() {
253253
/**
254254
* @ngdoc property
@@ -281,7 +281,7 @@ function $HttpProvider() {
281281
* If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
282282
* Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
283283
*
284-
**/
284+
*/
285285
var defaults = this.defaults = {
286286
// transform incoming response data
287287
transformResponse: [defaultHttpResponseTransform],
@@ -326,7 +326,7 @@ function $HttpProvider() {
326326
*
327327
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
328328
* otherwise, returns the current configured value.
329-
**/
329+
*/
330330
this.useApplyAsync = function(value) {
331331
if (isDefined(value)) {
332332
useApplyAsync = !!value;
@@ -350,7 +350,7 @@ function $HttpProvider() {
350350
*
351351
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
352352
* otherwise, returns the current configured value.
353-
**/
353+
*/
354354
this.useLegacyPromiseExtensions = function(value) {
355355
if (isDefined(value)) {
356356
useLegacyPromise = !!value;
@@ -371,9 +371,49 @@ function $HttpProvider() {
371371
* array, on request, but reverse order, on response.
372372
*
373373
* {@link ng.$http#interceptors Interceptors detailed info}
374-
**/
374+
*/
375375
var interceptorFactories = this.interceptors = [];
376376

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

@@ -397,6 +437,11 @@ function $HttpProvider() {
397437
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
398438
});
399439

440+
/**
441+
* A function to check request URLs against a list of allowed origins.
442+
*/
443+
var urlIsAllowedOrigin = urlIsAllowedOriginChecker(xsrfWhitelistedOrigins);
444+
400445
/**
401446
* @ngdoc service
402447
* @kind function
@@ -773,25 +818,42 @@ function $HttpProvider() {
773818
* which the attacker can trick an authenticated user into unknowingly executing actions on your
774819
* website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
775820
* $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
776-
* header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
777-
* cookie, your server can be assured that the XHR came from JavaScript running on your domain.
778-
* The header will not be set for cross-domain requests.
821+
* header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read
822+
* the cookie, your server can be assured that the XHR came from JavaScript running on your
823+
* domain.
779824
*
780825
* To take advantage of this, your server needs to set a token in a JavaScript readable session
781826
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
782-
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
783-
* that only JavaScript running on your domain could have sent the request. The token must be
784-
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
827+
* server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be
828+
* sure that only JavaScript running on your domain could have sent the request. The token must
829+
* be unique for each user and must be verifiable by the server (to prevent the JavaScript from
785830
* making up its own tokens). We recommend that the token is a digest of your site's
786831
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
787832
* for added security.
788833
*
789-
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
790-
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
791-
* or the per-request config object.
834+
* The header will &mdash; by default &mdash; **not** be set for cross-domain requests. This
835+
* prevents unauthorized servers (e.g. malicious or compromized 3rd-party APIs) from gaining
836+
* access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you
837+
* want to, you can whitelist additional origins to also receive the XSRF token, by adding them
838+
* to {@link ng.$httpProvider#xsrfWhitelistedOrigins xsrfWhitelistedOrigins}. This might be
839+
* useful, for example, if your application, served from `example.com`, needs to access your API
840+
* at `api.example.com`.
841+
* See {@link ng.$httpProvider#xsrfWhitelistedOrigins $httpProvider.xsrfWhitelistedOrigins} for
842+
* more details.
843+
*
844+
* <div class="alert alert-danger">
845+
* **Warning**<br />
846+
* Only whitelist origins that you have control over and make sure you understand the
847+
* implications of doing so.
848+
* </div>
849+
*
850+
* The name of the cookie and the header can be specified using the `xsrfCookieName` and
851+
* `xsrHeaderName` properties of either `$httpProvider.defaults` at config-time,
852+
* `$http.defaults` at run-time, or the per-request config object.
792853
*
793854
* In order to prevent collisions in environments where multiple Angular apps share the
794-
* same domain or subdomain, we recommend that each application uses unique cookie name.
855+
* same domain or subdomain, we recommend that each application uses a unique cookie name.
856+
*
795857
*
796858
* @param {object} config Object describing the request to be made and how it should be
797859
* processed. The object has following properties:
@@ -1262,7 +1324,7 @@ function $HttpProvider() {
12621324
// if we won't have the response in cache, set the xsrf headers and
12631325
// send the request to the backend
12641326
if (isUndefined(cachedResp)) {
1265-
var xsrfValue = urlIsSameOrigin(config.url)
1327+
var xsrfValue = urlIsAllowedOrigin(config.url)
12661328
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
12671329
: undefined;
12681330
if (xsrfValue) {

src/ng/urlUtils.js

+45-4
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,18 @@ var urlParsingNode = window.document.createElement("a");
1010
var originUrl = urlResolve(window.location.href);
1111

1212

13+
/**
14+
* Compare the origins of two parsed URL objects.
15+
*
16+
* @param {Object} url1 - The first parsed URL object to compare.
17+
* @param {Object} url2 - The second parsed URL object to compare.
18+
*
19+
* @returns {boolean} - Whether the origins of the two URLs are the same.
20+
*/
21+
function sameOrigin(url1, url2) {
22+
return (url1.protocol === url2.protocol) && (url1.host === url2.host);
23+
}
24+
1325
/**
1426
*
1527
* Implementation Notes for non-IE browsers
@@ -83,14 +95,43 @@ function urlResolve(url) {
8395
}
8496

8597
/**
86-
* Parse a request URL and determine whether this is a same-origin request as the application document.
98+
* Parse a request URL and determine whether this is a same-origin request as the application
99+
* document.
87100
*
88101
* @param {string|object} requestUrl The url of the request as a string that will be resolved
89102
* or a parsed URL object.
90103
* @returns {boolean} Whether the request is for the same origin as the application document.
91104
*/
92105
function urlIsSameOrigin(requestUrl) {
93-
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
94-
return (parsed.protocol === originUrl.protocol &&
95-
parsed.host === originUrl.host);
106+
var parsedUrl = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
107+
return sameOrigin(parsedUrl, originUrl);
108+
}
109+
110+
/**
111+
* Create a function that can check a URL's origin against a list of allowed/whitelisted origins.
112+
* The current location's origin is implicitly trusted.
113+
*
114+
* @param {string[]} whitelistedOriginUrls - A list of URLs (strings), whose origins are trusted.
115+
*
116+
* @returns {Function} - A function that receives a URL (string or parsed URL object) and returns
117+
* whether it is of an allowed origin.
118+
*/
119+
function urlIsAllowedOriginChecker(whitelistedOriginUrls) {
120+
var parsedAllowedOriginUrls = [originUrl].concat(whitelistedOriginUrls.map(urlResolve));
121+
122+
/**
123+
* Check whether the specified URL (string or parsed URL object) has an origin that is allowed
124+
* based on a list of whitelisted-origin URLs. The current location's origin is implicitly
125+
* trusted.
126+
*
127+
* @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be
128+
* resolved or a parsed URL object).
129+
*
130+
* @returns {boolean} - Whether the specified URL is of an allowed origin.
131+
*/
132+
return function urlIsAllowedOrigin(requestUrl) {
133+
var parsedUrl = isString(requestUrl) ? urlResolve(requestUrl) : requestUrl;
134+
135+
return parsedAllowedOriginUrls.some(sameOrigin.bind(null, parsedUrl));
136+
};
96137
}

test/.jshintrc

+1
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@
126126
/* urlUtils.js */
127127
"urlResolve": false,
128128
"urlIsSameOrigin": false,
129+
"urlIsAllowedOriginChecker": false,
129130

130131
/* jasmine / karma */
131132
"it": false,

0 commit comments

Comments
 (0)