Search code examples
cookiessubdomain

Why isn't this cookie sent to other subdomains?


We have an authentication API for signing in and a file download API that serves protected files.

The authentication API lives at authentication.api.mysite.com and returns the following header on a successful sign-in:

Set-Cookie: sessionId=QpiYzBXNNhiMZQSdWfKiDM; SameSite=None; Secure; HttpOnly; Domain=.mysite.com

(I have also tried Domain=.mysite.com, i.e. with a leading dot, without luck.)

The file API lives at files.api.mysite.com and allows clients to download protected files given the following request header:

Cookie: sessionId=QpiYzBXNNhiMZQSdWfKiDM

The APIs are used by a web app that lives at something.othersite.com. In the browser dev tools, I see that the sign-in response has the cookie in the "Cookies" tab, so I know it's set. And the cookie is sent to other requests against the authentication API. But no cookies are sent in requests to the file API.

As I understand it (e.g. MDN), if Domain is set to mysite.com (or .mysite.com judging by some other sources) then it should also be sent to api.mysite.com and whatever.api.mysite.com. But it's not sent to other subdomains.

What are we doing wrong? How can we get the browser to pass the cookie set by the authentication API on to the file API?

In case it's relevant: Both APIs use CORS, set up to allow the specific host we're using (not wildcard), allow any method, allow any header, allow credentials, and expose a set of headers I don't think is relevant (Set-Cookie isn't included there, but it made no difference when we added it).


Solution

  • The cookie was correct; the problem was caused by how the front-end called the APIs. The front-end uses axios, and the solution was to use the withCredentials option, e.g.:

    axios.post(
      url,
      data, 
      { headers: headers,
        withCredentials: true }
    )