diff --git a/src/ng/http.js b/src/ng/http.js index fff887176..4dd475eab 100644 --- a/src/ng/http.js +++ b/src/ng/http.js @@ -674,14 +674,6 @@ function $HttpProvider() { config.headers = headers; config.method = uppercase(config.method); - var xsrfValue = urlIsSameOrigin(config.url) - ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] - : undefined; - if (xsrfValue) { - headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; - } - - var serverRequest = function(config) { headers = config.headers; var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); @@ -957,8 +949,17 @@ function $HttpProvider() { } } - // if we won't have the response in cache, send the request to the backend + + // if we won't have the response in cache, set the xsrf headers and + // send the request to the backend if (isUndefined(cachedResp)) { + var xsrfValue = urlIsSameOrigin(config.url) + ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } diff --git a/test/ng/httpSpec.js b/test/ng/httpSpec.js index e996c6dff..9b12dbc3c 100644 --- a/test/ng/httpSpec.js +++ b/test/ng/httpSpec.js @@ -860,6 +860,25 @@ describe('$http', function() { $httpBackend.flush(); })); + + it('should check the cache before checking the XSRF cookie', inject(function($browser, $cacheFactory) { + var testCache = $cacheFactory('testCache'), + executionOrder = []; + + spyOn($browser, 'cookies').andCallFake(function() { + executionOrder.push('cookies'); + return {'XSRF-TOKEN':'foo'}; + }); + spyOn(testCache, 'get').andCallFake(function() { + executionOrder.push('cache'); + }); + + $httpBackend.expect('GET', '/url', undefined).respond(''); + $http({url: '/url', method: 'GET', cache: testCache}); + $httpBackend.flush(); + + expect(executionOrder).toEqual(['cache', 'cookies']); + })); });