2

I'm trying to login from one of my servers to another in order to send cross-origin requests that requires being logged. is it possible?

I have two web servers, A and B. Lets say www.a.com and www.b.com. B has an API that can be used only if the client is logged in. I need to use that API from A clients.

So, I send from A client an ajax (post) login request to B. B responses with CORS headers, the session cookie and a successful redirection to B's home/index.

But when I make a second ajax request (jsonp request) from A client to B server, this request doesn't send the previous session cookie received, therefore the login request failed.

If I login to www.b.com manually (in a second browser tab), all requests from A to B are successful detected as a logged user, so, the B API works from A.

I think that the session cookie received from my login requests is not being saved to the browser.

This is my login request:

$.post("www.b.com/login", { 'j_username': 'username', 'j_password': 'password' } );

Using:

jqXHR.withCredentials = true;
settings.crossDomain = true;

Response headers:

Access-Control-Allow-Headers:x-requested-with
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:*
...
Location:http://www.b.com/home
...
Set-Cookie:JSESSIONID=tY++VWlMSxTTUkjvyaRelZ0o; Path=/

The cookie received is being saved to www.a.com or to www.b.com? How can I set this cookie to www.b.com from an A client ajax request? I think that is the problem.

Alstrat
  • 145
  • 13
  • When `b.com` responds with a `Set-Cookie` header, then that sets the cookie for `b.com`, which seems to be what you want. However, I think you need to specify a non-wildcard allowed origin (i.e., `http://www.a.com` instead of `*`) because [credentialed CORS requests fail if the server gives a wildcard `Access-Control-Allow-Origin:*` response](http://stackoverflow.com/q/19743396/710446). – apsillers Oct 24 '16 at 15:55

1 Answers1

3

As apsillers said, we can't use the wildcard Access-Control-Allow-Origin:*. But this doesn't solved the problem.

I was setting jqXHR.withCredentials = true; inside a beforeSend handler function.

$.post({
        ...
        beforeSend: function(xhr) {
            xhr.withCredentials = true;
        },
        ...
});

And for some reason, this doesn't work. I had to set the use of credentials directly:

$.post({
        ...
        xhrFields: {
            withCredentials: true
        },
        ...
});

This code works perfectly !

Thanks you.

Alstrat
  • 145
  • 13