After authenticating with a remove API endpoint the browser has a JWT token cookie.
I can confirm this by looking a the network request tab, and also by getting an API endpoint that requires auth. using Firefox. Firefox automatically makes a GET request to the endpoint, and because the Hostname matches, it automatically includes the credentials. I get a JSON response, 200 OK.
Now, the problem, when trying to develop the site locally, using a local server, on localhost, the API requests are being sent to the remote dev API endpoints, but the return 401 unauthorized, because Firefox is not sending the credentials.
Shouldn’t Firefox be including the credentials, because the hostname matches? Even though the site hostname is localhost?
I have disabled CORS in firefox, but no on the remote server.
I can see this has worked, because otherwise the network tab says the the request was blocked because of CORS.
How to authenticate to a remote API endpoint on a localhost site using cookies?
On the fetch request, credentials is set to ‘include’.
Same issue in chrome.
2
Answers
Firefox 'Enhanced Tracking Protection' was overriding my cookie. ETP in strict mode stops all cross-site cookies from being sent. After disabling ETP on the localhost site the cookie started being attached to the remote api requests.
Cookie flags:
I'm still not clear on whether Firefox Developer defaults to Lax or None for SameSite. About:config has a setting called network.cookie.sameSite.laxByDefault which is set to 'false'... but that could be a legacy setting, as this site contradicts it, stating default is Lax.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
Cookie rules are explained in RFC6265 and I suspect you are running into same-site rules from section 4.1.2.7.
If the cookie is considered third party (from a domain not in the same site as the web origin), browsers will refuse to save or send the cookie, when the server delivers it in a set-cookie response header. This is a user privacy protection.
INVALID EXAMPLE
VALID EXAMPLE
This setup can be enabled by adding an entry like this to your hosts file, then using that URL in the browser:
RULES
For the web origin and API to be in the same site, the port can be different, but the scheme (http or https) must match. If the remote API URL uses https you will need to run the web app locally with https also.
CORS must also be configured correctly. I would enable that by adding the development web origin to those allowed by the API. Personally I avoid using localhost for this type of solution.