HTTP Cookies and Ajax requests over HTTPS - ajax

I know this has been asked before in various forms, but I can't seem to get around the problem.
I have tried using both jQuery and the native JS API to make the Ajax requests.
My situation is the following (see attached diagram):
Browser makes HTTP request
Server responds and sets persistent Cookie
Browser makes HTTP Ajax request, Cookie is there alright
Server responds as expected, updates Cookie
Browser makes HTTPS Ajax request, Cookie is not there anymore (?!)
Server gives "default" response, since there is no Cookie (unintended behaviour)
Before anybody starts a lecture on cross-domain requests let me state a couple of things:
I know that this is a cross-domain request (different protocol), and that's why the Server sets the Access-Control-Allow-Origin header in the response (and I am using Chrome and Firefox, both of which support CORS)
What I also know, though, is that the HTTP cookie ought to be manageable over HTTPS (see here) since the host is the same
(EDIT) The cookie is properly set for the general domain (e.g. .domain.ext) and neither the HttpOnly nor the Secure flags are set
So, why, why, why doesn't the browser pass on the cookie when making the HTTPS Ajax call? Any ideas? I am about to lose my mind...
+-----------+ HTTP Request +-----------+
|Browser |+---------------->|Server |
+-----------+ +-----------+
HTTP Response
<----------------+
Set-cookie
Ajax HTTP Req.
+---------------->
Cookie (OK)
HTTP Response
<----------------+
Set-cookie (OK)
Ajax HTTPS Req.
+---------------->
No Cookie (!!!)

Ok, found the solution to the cookie problem.
See XHR specs, jQuery docs and StackOverflow.
The solution to have the cookies sent when switching protocol and/or subdomain is to set the withCredentials property to true.
E.g. (using jQuery)
$.ajax( {
/* Setup the call */
xhrFields: {
withCredentials: true
}
});

Document.cookie and Ajax Request does not share the cookie. Otherwise, ajax can't access the cookies from document.cookie or the response headers. They can only be controlled by the remote domain.
If you first get response including cookie from server by ajax, Since that you can request ajax communication with cookie to server.
For this case, you write such as below code (jQuery)
$.ajax({
xhrFields : {
withCredentials : true
}
});
See this article and demo

Related

Cookie in AJAX response from other domain not honored - are there workarounds

I have a server-side API on the domain api.example.com
User is visiting www.website.com where a script makes an XmlHttpRequest to api.example.com and gets a response with a cookie.
It appears the API's response cookie is not honored by the HTTP agent.
I'm aware of the non-cross-domain-leaking-cookie policy, but I thought the domain here would be api.example.com. Seems I guessed wrong.
Is there some other way that my API on api.example.com could remember user data from one site to another? If not, how could services like Criteo and other retargeting sites work, from this point of view?
Make sure your API set:
Access-Control-Allow-Credentials header to true in possible preflight response and regular response,
Access-Control-Allow-Origin header to value of the origin from the actual request,
and client sets XMLHttpRequest.withCredentials to true.

Angular resource how to keep ajax header and enable cors at the same time

In my ng-resource files, I enable the ajax header:
var app = angular.module('custom_resource', ['ngResource'])
app.config(['$httpProvider', function($httpProvider) {
//enable XMLHttpRequest, to indicate it's ajax request
//Note: this disables CORS
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}])
app.factory('Article', ['$resource', function($resource) {
return $resource('/article/api/:articleId', {articleId: '#_id'}, {
update: {method: 'PUT'},
query: {method: 'GET', isArray: true}
})
}])
So that I can separate ajax and non-ajax request and response accordingly (to send json data like res.json(data), or to send the entire html page like res.render('a.html')
for example, in my error handler, I need to decide to render error.html page or to just send a error message:
exports.finalHandler = function(err, req, res, next) {
res.status(err.status || 500)
var errorMessage = helper.isProduction() ? '' : (err.message || 'unknown error')
if (req.xhr) {
res.json({message: errorMessage})
}
else {
res.render(dir.error + '/error_page.ejs')
}
}
But now I need to do CORS request to other sites. Is it possible to do CORS request while keeping the ajax header? or other ways I can identify ajax and non-ajax request from server?
In case my question is not clear, heres a relevant article about angular and CORS
http://better-inter.net/enabling-cors-in-angular-js/
Basically, we need to delete xhr header to enable cors for other server, but I need the header for my own server
EDIT 2:
today I tried integrating google map and I got this error:
XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?address=Singapore&sensor=false. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Setting custom headers on XHR requests triggers a preflight request.
So, it doesn't disable CORS but your server is most likely not handling the preflight request.
Inspired from this post: https://remysharp.com/2011/04/21/getting-cors-working
The solution should be to use the cors module and add the following to your node.js code before your routes:
var corsOptions = {
origin: true,
methods: ['GET', 'PUT', 'POST'],
allowedHeaders: ['X-Requested-With','Content-Type', 'Authorization']
};
app.options('*', cors(corsOptions)); //You may also be just fine with the default options
You can read more at: https://github.com/expressjs/cors
you may try to use cors package
First, to address you primary concern is it possible to do CORS request while keeping the ajax header?: the answer is YES, provided the sites you are accessing allow requests from you or any other external clients at all.
You wrote:
//Note: this disables CORS
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
But I don't understand what you mean by, it "disables CORS". The X-Requested-With header is not a standard header, and the known effect of adding a non-standard header to a request (made from a browser) is the triggering of a pre-flight request [3].
If the other sites you are interested in would set their servers to refuse processing of requests that do not originate from their own domain, then whether you set that header or not, your request should fail.
It seems everything is working fine for you, for requests sent to you own server. Otherwise you can solve the problem by appending the Access-Control-Allow-Origin header in your server responses as follows:
if you need to allow requests from specific domains
response.set("Access-Control-Allow-Origin", "one-host-domain, your-host-domain, some-other-host-domain"); // second argument is a comma-delimited list of allowed domains
(It may be better for you to actually check the request object for the origin, and if it's permitted based on presence in a pre-determined list, then send back the exact same origin).
If you need to permit all requests regardless of its origin
response.set("Access-Control-Allow-Origin", "*");
That should do, and I hope it clears your doubts for you.
More info on handling CORS when using AJAX: 0, 1 & 2.
EDIT
Following exchanges in the comment, I add the following points to support this answer further.
As it is today, the only side that needs disabling/enabling CORS in the client-server system is the server. All modern browsers allow cross origin requests by default and you don't need to do anything additional to support that capability. I understood that you're adding a custom header to distinguish AJAX requests from the rest?? AFAIK, that header changes nothing about how requests are made by browsers.
Here is how all cross-origin requests are handled by browsers today: for all request methods (but usually with the exception of GET), browsers send a pre-flight request with the OPTION method. If the destination server allows it, the actual request is then sent, otherwise the request fails. In the case where the servers, responds with a refusal there's nothing you nor whatever library you use can do about it. This is the fact from my own experience.
There are 3 solutions that come to my mind:
1. Ask site's admin to enable x-requested-with header in CORS.
2. Use proxy server.
3. Send request without x-requested-with header.
This article should make it clear how CORS works and how to make CORS requests.
Particularly "Simple requests" section and "Access-Control" section, especially access-control-allow-headers description is important in this case.
As it says: for simple requests access-control-allow-origin is enough. However if the request includes custom header (a header which is not included by default, such as x-requested-with header), the preflight request is triggered, and server's response to this request should enable this custom header in access-control-allow-headers by setting its value to either "*" or to the name of a custom header (x-requested-with).
Hope it makes it a little bit clearer.

Disable preflight OPTION request when sending a cross domain request with custom HTTP header

I've just found out that my browser was sending an extra "OPTION" request when trying to make a cross domain ajax call with a custom http header.
I presume it is called "preflight request".
Is it possible to disable this functionality and just send the initial request ?
This is my javascript testing code :
$(document).ready(function() {
$.ajax({
url: "http://google.fr",
crossDomain: true,
headers: {
"X-custom-parameter": true
}
});
});
No, it is definitely not possible to bypass the CORS preflight request. The preflight request exists to allow cross-domain requests in a safe manner. In your example above, you are trying to access google.fr, but google.fr doesn't support CORS. There is no way around this for Google, since Google doesn't support cross-domain requests on its web page. In general, if you have ownership of the server, your options are to support CORS, support alternative cross-domain hacks like JSON-P, or use a server-side proxy.

Can Firefox be made to accept third-party cookies from an AJAX response header?

I'm writing some code that makes an AJAX request to our web server. Our server runs some logic and then responds with some JSON. It may also respond with a set-cookie header:
Set-Cookie: our_organisation=[uuid]; domain=.our_organisation.com; path=/; expires=[soon]
It works in Chrome and Safari as far as I can tell, but not in Firefox. Firefox will accept the cookie if it's an image request instead. Am I doing something wrong here?
I already had a problem where I couldn't read the AJAX response on the client side in Firefox; this was fixed by setting Access-Control-Allow-Origin: * in the response header.
This is a cross-site XMLHttpRequest?
If so, per http://dev.w3.org/2006/webapi/XMLHttpRequest-2/ withCredentials defaults to false so the "credentials flag" used for CORS is set to false, and then per http://dvcs.w3.org/hg/cors/raw-file/tip/Overview.html the "block cookies" flag is set during the HTTP get, and per http://www.whatwg.org/specs/web-apps/current-work/multipage/fetching-resources.html#fetch that means Set-Cookie headers are ignored. Sounds like Chrome and Safari are just not following the specs here.
You can set withCredentials = true on the XHR object to send cookies. But note that if you do that you have to list an actual origin in Access-Control-Allow-Origin; you can't just use *.

Can an AJAX response set a cookie?

Can an AJAX response set a cookie? If not, what is my alternative solution? Should I set it with Javascript or something similar?
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist,
discard and send cookies (as received in the Set-Cookie response
header, and sent in the Cookie header) as applicable.
Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.
AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.
For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

Resources