Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel CORS subdomain session

I'm having problems with Auth::check() in subdomain via ajax requests.. Scenario: 2 subdomains

www.testing.dev
api.testing.dev

Single login/session between those two.. in the laravel config/session.php i have set 'domain' => ".testing.dev", and everything is working fine, i'm able to login in one page and continue to be logged in the other page also!

But when i use ajax there is a problem.. scenario: being in the api.testing.dev, i perform with firebug, js, whatever

$.ajax({
    url: 'http://api.testing.dev/who',
    type: 'GET',
    cache: false
});

the api.stesting.dev/who returns:

public function getWho(){
    return var_dump( Auth::user() );
}

The response is the information of my account! all correct..

if from the www.testing.dev i perform the same ajax query, i get Auth::check() returning null. Though i get normal response, so no problem with cross domain setup.. here are my headers in in the route for the api.testing.dev

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: OPTIONS, POST, GET, PUT, DELETE');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Credentials: true');

The website is running in localhost with wamp.

Edit: with the default session driver 'driver' => 'file', after the initial login, in the app/storage/sessions there is one file. And if i go from one subdomain to another, no other files are generated. Though when i preform a CORS ajax, every time a new file is generated...

like image 734
ActonDev Avatar asked Nov 10 '22 06:11

ActonDev


1 Answers

Seeing your configuration, maybe you have the same problem that I had. I wasn't using Auth, but sessions and got null everytime. I solved it by changing this:

header('Access-Control-Allow-Origin: *');
...
header('Access-Control-Allow-Credentials: true');

to this:

header('Access-Control-Allow-Origin: http://localhost:9000');
...
header('Access-Control-Allow-Credentials: true');

The reason that I found is that when you use the credentials it needs to specify the origin for security purposes, and for the AJAX request it needs to specify the credentials, too. I use Angular and I did this with $httpProvider.defaults.withCredentials=true;, but I really don't know the corresponding instruction for jQuery, but I hope you can find it.

Check the headers of the request and responses with your favourite debugger (Firebug for me). They should have a cookie attribute (it contains something with "laravel", "token", etc.) that the second time should be equal to the first response header.

like image 61
Luis Gonzalez Avatar answered Nov 15 '22 04:11

Luis Gonzalez