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

Commit 308f3bf

Browse files
feat($http): specify the JSONP callback via the callbackParam config value
The query parameter that will be used to transmit the JSONP callback to the server is now specified via the `callbackParam` config value, instead of using the `JSON_CALLBACK` placeholder. * Any use of `JSON_CALLBACK` in a JSONP request URL will cause an error. * Any request that provides a parameter with the same name as that given by the `callbackParam` config property will cause an error. This is to prevent malicious attack via the response from an app inadvertently allowing untrusted data to be used to generate the callback parameter. BREAKING CHANGE You can no longer use the `JSON_CALLBACK` placeholder in your JSONP requests. Instead you must provide the name of the query parameter that will pass the callback via the `callbackParam` property of the config object, or app-wide via the `$http.defaults.callbackParam` property, which is `callback` by default. Before this change: ``` $http.json('trusted/url?callback=JSON_CALLBACK'); $http.json('other/trusted/url', {params:cb:'JSON_CALLBACK'}); ``` After this change: ``` $http.json('trusted/url'); $http.json('other/trusted/url', {callbackParam:'cb'}); ```
1 parent 3d1512b commit 308f3bf

File tree

4 files changed

+123
-17
lines changed

4 files changed

+123
-17
lines changed
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
@ngdoc error
2+
@name $http:badjsonp
3+
@fullName Bad JSONP Request Configuration
4+
@description
5+
6+
This error occurs when the URL generated from the configuration object contains a parameter with the same name as the configured `callbackParam`
7+
property; or when it contains a parameter whose value is `JSON_CALLBACK`.
8+
9+
`$http` JSON requests need to attach a callback query parameter to the URL. The name of this parameter is specified in the configuration
10+
object (or in the defaults) via the `callbackParam` property. You must not provide your own parameter with this name in the configuration
11+
of the request.
12+
13+
In previous versions of Angular, you specified where to add the callback parameter value via the `JSON_CALLBACK` placeholder. This is no longer
14+
allowed.
15+
16+
To resolve this error, remove any parameters that have the same name as the `callbackParam`; and/or remove any parameters that have a value of `JSON_CALLBACK`.
17+
18+
For more information, see the {@link ng.$http#jsonp `$http.jsonp()`} method API documentation.

docs/content/guide/concepts.ngdoc

+1-1
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ The following example shows how this is done with Angular:
326326
var YAHOO_FINANCE_URL_PATTERN =
327327
'//query.yahooapis.com/v1/public/yql?q=select * from ' +
328328
'yahoo.finance.xchange where pair in ("PAIRS")&format=json&' +
329-
'env=store://datatables.org/alltableswithkeys&callback=JSON_CALLBACK';
329+
'env=store://datatables.org/alltableswithkeys';
330330
var currencies = ['USD', 'EUR', 'CNY'];
331331
var usdToForeignRates = {};
332332

src/ng/http.js

+50-3
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,10 @@ function $HttpProvider() {
286286
* If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
287287
* Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
288288
*
289+
* - **`defaults.callbackParam`** - `{string} - the name of the query parameter that passes the callback in a JSONP
290+
* request. The value of this parameter will be replaced with the expression generated by the {@link jsonpCallbacks}
291+
* service. Defaults to `'callback'`.
292+
*
289293
**/
290294
var defaults = this.defaults = {
291295
// transform incoming response data
@@ -309,7 +313,9 @@ function $HttpProvider() {
309313
xsrfCookieName: 'XSRF-TOKEN',
310314
xsrfHeaderName: 'X-XSRF-TOKEN',
311315

312-
paramSerializer: '$httpParamSerializer'
316+
paramSerializer: '$httpParamSerializer',
317+
318+
callbackParam: 'callback'
313319
};
314320

315321
var useApplyAsync = false;
@@ -964,7 +970,8 @@ function $HttpProvider() {
964970
method: 'get',
965971
transformRequest: defaults.transformRequest,
966972
transformResponse: defaults.transformResponse,
967-
paramSerializer: defaults.paramSerializer
973+
paramSerializer: defaults.paramSerializer,
974+
callbackParam: defaults.callbackParam
968975
}, requestConfig);
969976

970977
config.headers = mergeHeaders(requestConfig);
@@ -1168,6 +1175,22 @@ function $HttpProvider() {
11681175
* {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
11691176
* by explicitly trusted the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
11701177
*
1178+
* JSONP requests must specify a callback to be used in the response from the server. This callback
1179+
* is passed as as a query parameter in the request. You must specify the name of this parameter by
1180+
* setting the `callbackParam` property on the request config object.
1181+
*
1182+
* ```
1183+
* $http.jsonp('some/trusted/url', {callbackParam: 'callback'})
1184+
* ```
1185+
*
1186+
* You can also specify a global callback parameter key in `$http.defaults.callbackParam`.
1187+
* By default this is set to `callback`.
1188+
*
1189+
* <div class="alert alert-danger">
1190+
* You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
1191+
* parameter value should go.
1192+
* </div>
1193+
*
11711194
* If you would like to customise where and how the callbacks are stored then try overriding
11721195
* or decorating the {@link $jsonpCallbacks} service.
11731196
*
@@ -1271,9 +1294,10 @@ function $HttpProvider() {
12711294
cache,
12721295
cachedResp,
12731296
reqHeaders = config.headers,
1297+
isJsonp = lowercase(config.method) === 'jsonp',
12741298
url = config.url;
12751299

1276-
if (lowercase(config.method) === 'jsonp') {
1300+
if (isJsonp) {
12771301
// JSONP is a pretty sensitive operation where we're allowing a script to have full access to
12781302
// our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
12791303
url = $sce.getTrustedResourceUrl(url);
@@ -1284,6 +1308,11 @@ function $HttpProvider() {
12841308

12851309
url = buildUrl(url, config.paramSerializer(config.params));
12861310

1311+
if (isJsonp) {
1312+
// Check the url and add the JSONP callback placeholder
1313+
url = sanitizeJsonpCallbackParam(url, config.callbackParam);
1314+
}
1315+
12871316
$http.pendingRequests.push(config);
12881317
promise.then(removePendingReq, removePendingReq);
12891318

@@ -1418,5 +1447,23 @@ function $HttpProvider() {
14181447
}
14191448
return url;
14201449
}
1450+
1451+
function sanitizeJsonpCallbackParam(url, key) {
1452+
if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
1453+
// Throw if the url already contains a reference to JSON_CALLBACK
1454+
throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
1455+
}
1456+
1457+
var callbackParamRegex = new RegExp('([&?]' + key + '=)');
1458+
if (callbackParamRegex.test(url)) {
1459+
// Throw if the callback param was already provided
1460+
throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
1461+
}
1462+
1463+
// Add in the JSON_CALLBACK callback param value
1464+
url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
1465+
1466+
return url;
1467+
}
14211468
}];
14221469
}

test/ng/httpSpec.js

+54-13
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,7 @@ describe('$http', function() {
622622
expect(r.headers()).toEqual(Object.create(null));
623623
});
624624

625-
$httpBackend.expect('JSONP', '/some').respond(200);
625+
$httpBackend.expect('JSONP', '/some?callback=JSON_CALLBACK').respond(200);
626626
$http({url: $sce.trustAsResourceUrl('/some'), method: 'JSONP'}).then(callback);
627627
$httpBackend.flush();
628628
expect(callback).toHaveBeenCalledOnce();
@@ -1030,39 +1030,80 @@ describe('$http', function() {
10301030
});
10311031

10321032
it('should have jsonp()', function() {
1033-
$httpBackend.expect('JSONP', '/url').respond('');
1033+
$httpBackend.expect('JSONP', '/url?callback=JSON_CALLBACK').respond('');
10341034
$http.jsonp($sce.trustAsResourceUrl('/url'));
10351035
});
10361036

10371037

10381038
it('jsonp() should allow config param', function() {
1039-
$httpBackend.expect('JSONP', '/url', undefined, checkHeader('Custom', 'Header')).respond('');
1039+
$httpBackend.expect('JSONP', '/url?callback=JSON_CALLBACK', undefined, checkHeader('Custom', 'Header')).respond('');
10401040
$http.jsonp($sce.trustAsResourceUrl('/url'), {headers: {'Custom': 'Header'}});
10411041
});
10421042
});
10431043

10441044
describe('jsonp trust', function() {
10451045
it('should throw error if the url is not a trusted resource', function() {
10461046
var success, error;
1047-
$http({method: 'JSONP', url: 'http://example.org/path?cb=JSON_CALLBACK'}).catch(
1048-
function(e) { error = e; }
1049-
);
1047+
$http({method: 'JSONP', url: 'http://example.org/path'})
1048+
.catch(function(e) { error = e; });
10501049
$rootScope.$digest();
10511050
expect(error.message).toContain('[$sce:insecurl]');
10521051
});
10531052

10541053
it('should accept an explicitly trusted resource url', function() {
1055-
$httpBackend.expect('JSONP', 'http://example.org/path?cb=JSON_CALLBACK').respond('');
1056-
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path?cb=JSON_CALLBACK')});
1054+
$httpBackend.expect('JSONP', 'http://example.org/path?callback=JSON_CALLBACK').respond('');
1055+
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path')});
10571056
});
10581057

10591058
it('jsonp() should accept explictly trusted urls', function() {
1060-
$httpBackend.expect('JSONP', '/url').respond('');
1059+
$httpBackend.expect('JSONP', '/url?callback=JSON_CALLBACK').respond('');
10611060
$http({method: 'JSONP', url: $sce.trustAsResourceUrl('/url')});
10621061

1063-
$httpBackend.expect('JSONP', '/url?a=b').respond('');
1062+
$httpBackend.expect('JSONP', '/url?a=b&callback=JSON_CALLBACK').respond('');
10641063
$http({method: 'JSONP', url: $sce.trustAsResourceUrl('/url'), params: {a: 'b'}});
10651064
});
1065+
1066+
it('should error if the URL contains a JSON_CALLBACK parameter', function() {
1067+
var error;
1068+
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path?callback=JSON_CALLBACK')})
1069+
.catch(function(e) { error = e; });
1070+
$rootScope.$digest();
1071+
expect(error.message).toContain('[$http:badjsonp]');
1072+
1073+
error = undefined;
1074+
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path?other=JSON_CALLBACK')})
1075+
.catch(function(e) { error = e; });
1076+
$rootScope.$digest();
1077+
expect(error.message).toContain('[$http:badjsonp]');
1078+
});
1079+
1080+
it('should error if a param contains a JSON_CALLBACK value', function() {
1081+
var error;
1082+
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path'), params: {callback: 'JSON_CALLBACK'}})
1083+
.catch(function(e) { error = e; });
1084+
$rootScope.$digest();
1085+
expect(error.message).toContain('[$http:badjsonp]');
1086+
1087+
error = undefined;
1088+
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path'), params: {other: 'JSON_CALLBACK'}})
1089+
.catch(function(e) { error = e; });
1090+
$rootScope.$digest();
1091+
expect(error.message).toContain('[$http:badjsonp]');
1092+
});
1093+
1094+
it('should error if there is already a param matching the callbackParam key', function() {
1095+
var error;
1096+
$http({ method: 'JSONP', url: $sce.trustAsResourceUrl('http://example.org/path'), params: {callback: 'evilThing'}})
1097+
.catch(function(e) { error = e; });
1098+
$rootScope.$digest();
1099+
expect(error.message).toContain('[$http:badjsonp]');
1100+
1101+
error = undefined;
1102+
$http({ method: 'JSONP', callbackParam: 'cb', url: $sce.trustAsResourceUrl('http://example.org/path'), params: {cb: 'evilThing'}})
1103+
.catch(function(e) { error = e; });
1104+
$rootScope.$digest();
1105+
expect(error.message).toContain('[$http:badjsonp]');
1106+
});
10661107
});
10671108

10681109
describe('callbacks', function() {
@@ -1524,11 +1565,11 @@ describe('$http', function() {
15241565
}));
15251566

15261567
it('should cache JSONP request when cache is provided', inject(function($rootScope) {
1527-
$httpBackend.expect('JSONP', '/url?cb=JSON_CALLBACK').respond('content');
1528-
$http({method: 'JSONP', url: $sce.trustAsResourceUrl('/url?cb=JSON_CALLBACK'), cache: cache});
1568+
$httpBackend.expect('JSONP', '/url?callback=JSON_CALLBACK').respond('content');
1569+
$http({method: 'JSONP', url: $sce.trustAsResourceUrl('/url'), cache: cache});
15291570
$httpBackend.flush();
15301571

1531-
$http({method: 'JSONP', url: $sce.trustAsResourceUrl('/url?cb=JSON_CALLBACK'), cache: cache}).success(callback);
1572+
$http({method: 'JSONP', url: $sce.trustAsResourceUrl('/url'), cache: cache}).success(callback);
15321573
$rootScope.$digest();
15331574

15341575
expect(callback).toHaveBeenCalledOnce();

0 commit comments

Comments
 (0)