Frage

I'm trying to implement some code that will allow me to have one sub-domain communicate with another sub-domain, e.g. one.example.com and two.example.com. The two sites have the ability to share cookies and session data as I have set the cookie to use .example.com.

When I visit either site via standard HTTP I can dump the session and see the expected data. However if I do this via JavaScript with jQuery $.ajax() the dumped session data is empty. In both cases I use PHP to dump the session data.

I have tried the following solution but to no luck yet (http://forum.kohanaframework.org/discussion/9895/problem-session-expired-with-ajax/p1). I'm also using a slightly newer version of Kohana (3.3).

I've also tried setting the headers as soon as they reach the controller:

$this->response->headers('Access-Control-Allow-Origin', 'http://one.example.com');
$this->response->headers('Access-Control-Allow-Credentials', 'true');
$this->response->headers('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');

However the Chrome inspector still shows the Access-Control-Allow-Origin as *.

War es hilfreich?

Lösung

The Problem

The problem I was having was due to a setting in my Apache config file which looked like this:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

In order to solve my particular problem I simple removed / commented out the above code as it was overriding the headers I sent from PHP.

My implemented solution was then quite simple. In the following example we'll assume that I am making a call from one.example.com (the main website) to two.example.com (a sub-site).

Kohana / PHP

In my PHP I set the following headers, I've chosen to do this in my parent Controller. You could create your own Cors class or helper if you prefer. Basically you don't want to have this code duplicated hundreds of times throughout your project.

$this->response->headers('Access-Control-Allow-Origin', 'http://one.example.com');
$this->response->headers('Access-Control-Allow-Credentials', 'true');
$this->response->headers('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');

JavaScript / jQuery

In my $.ajax() requests I then have to make sure to set the xhrFields.withCredentials property to true.

$.ajax({
    url: 'two.example.com',
    xhrFields: {
        withCredentials: true
    }
});

Or I could set it globally for all ajax requests like so:

$(document).ajaxSend(function (event, xhr, settings) {
    settings.xhrFields = {
        withCredentials: true
    };
});

For more information check the $.ajax documentation: http://api.jquery.com/jQuery.ajax/

Further Reading

For further information checkout the following resources:

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top