Why isn't this cookie sent to other subdomains? - cookies

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).

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 }
)

Related

Cookie not being set on angular client

I have a backend app in django python and it is being served on http://localhost:8000.
I have a angular frontend which is being served on http://localhost:4200.
I have disabled CORS on django.
On hitting the login api on http://localhost:8000/auth/login/, I am getting a valid response
along with the Set-Cookie header.
Here is my angular code to print the cookies:
this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response' }).subscribe(response => {
console.log("response is ", response);
var cookies = this.cookieService.getAll();//('cookies');
console.log("cookies is :", cookies);
It prints an empty object on console.
How do I make this work? I want to use cookies for authentication.
You are trying to set cross domain cookies, which will not work straight away. There are a few steps to follow to be able to do that.
Set withCredentials: true when making the authentication request from angular
this.http.post<any>('http://localhost:8000/auth/login/', this.LoginForm, { observe: 'response', withCredentials: true })
Configure your server to return the following CORS headers: Access-Control-Allow-Credentials: true and Access-Control-Allow-Origin: http://localhost:4200
Note
One of the cookies that you are setting is HttpOnly. As such, you cannot access it from Javascript (see documentation).
You may not need to access the cookies with JS anyway. If you just want to send the cookies in the next API requests, just pass withCredentials: true to HttpClient other api calls
this.http.get('http://localhost:8000/path/to/get/resource',
{ withCredentials: true }).subscribe(response => {
Set-Cookies:
In the example in the Question, both client and server are in the same domain, localhost.
On deployment, this may not be the case.
Let us assume the domains as below,
Client : client1.client.com
Server: server1.server.com
A http request from the Angular web app in client1.client.com to https://server1.server.com/api/v1/getSomething has Set-Cookie: JSESSIONID=xyz in the response header.
The cookie will be set on server1.server.com and NOT on client1.client.com.
You can enter server1.server.com in the URL bar and see the cookie being set.
withCredentials:
There is no need for the angular app to read the cookie and send it in the following requests. withCredentials property of http request can be used for this.
Refer: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Example:
public getSomething(): Observable<object> {
const httpOptions = {
withCredentials: true
};
return this.http.get(`${this.serverUrl}/getSomething`, httpOptions);
}
Refer: https://angular.io/api/common/http/HttpRequest
withCredentials will set the cookies from the server's domain in the requests to the server.
As mentioned before Set-Cookie: JSESSIONID=xyz in the response from server1.server.com will be set in server1.server.com. The Angular app in client1.client.com need not read it. withCredentials will take care of it.
cross domain issues:
When the server and client are in different domains, using withCredentials may not work in all browsers, as they are considered as third party cookies.
In my recent testing on May 2020, I found that withCredentials is not working in certain browsers when the client and server are in different domains.
In Safari, the issue occurs when "Prevent cross-site tracking" is enabled (by default). The issue is prevented by disabling the same. https://support.apple.com/en-in/guide/safari/sfri40732/mac
In Android apps, the issue can be avoided by using Chrome Custom Tabs instead of Android WebView. https://github.com/NewtonJoshua/custom-tabs-client , https://developer.chrome.com/multidevice/android/customtabs
Same domain:
Looks like mainstream browsers are moving to block third-party cookies.
Safari - Full Third-Party Cookie Blocking and More
Chrome (by 2022) - Building a more private web: A path towards making third party cookies obsolete
The solution is to have both the client and server in the same domain.
Client: client1.myapp.com
Server: server1.myapp.com
And in the Set-Cookie response include the root domain too.
Example: "JSESSIONID=xyz; Domain=.myapp.com; Path=/"
This will make sure the cookies are set in all cases.

Set-Cookie from a server to an XHR client in a different domain, setting the domain to the client's domain, should it work?

tl;dr, an XHR client in domain A is sending a request to a server in domain B, server responds with a Set-Cookie with Domain=A (the client's domain, the XHR's Origin), all CORS headers set correctly, should it work?
It's well known that one can't set a cookie to another domain. ( How to set a cookie for another domain
However given the following scenario:
Actors:
Client in domain A, a web based client
Server in domain B, setup with CORS headers permitting A as origin, including Access-Control-Allow-Credentials set to true
Communication flow 1 (baseline):
Client is issuing a simple GET request to the Server
Server responds with a cookie, and sets the Domain property to be of the server (Domain=B)
Client is sending another HXR request and has withCredentials=true
The cookie is sent back to the server without any issues
Note: the cookie sent in step #1 is not showing in document.cookies, even if it was not set as httpOnly (since it doesn't
belong to the client's domain). Also attempts to get it from the xhr
via looking at the "Set-Cookie" header, you'll be blocked, by design:
https://fetch.spec.whatwg.org/#forbidden-response-header-name it will
even won't show in Chrome dev tools under the network tab! but it will
still be sent)
Communication flow 2 (my question):
Client is issuing a simple GET request to the Server
Server responds with a cookie, but sets the Domain property to be of the client (Domain=A)
Client is sending an HXR request and has withCredentials=true
The cookie is not sent back and doesn't seem to be stored anywhere
Why am I a bit surprised? Since the XHR origin is A and it requests something that sets the cookie to domain A (if I look in Postman I clearly see the Set-Cookie header being sent with Domain being the same as the request's Origin), and I have the most permissive CORS setting for that, what's the reasoning behind not letting me do it? (I was expecting it to fail, but still made me wonder)
Questions
Where is the best place in the spec/RFC that it clarifies that this won't work also for XHR where the cookie Domain equals the Origin
What is the attack vector in scenario 2 if theoretically the browser did allow the server to store the cookie if and only if the Origin is the same as the cookie Domain and the CORS origin allows that Origin.
Is there another way to make it work? Maybe it works but my POC was setup incorrectly?
Appendix: Reasoning
I'm looking for a way to have a cross origin CSRF using something like the Cookie to header token method, but due to the cross origin issue, it seems that it's impossible. The only workaround I thought of is sending the CSRF token as a header from the server, then the client can just save it as a cookie it can access later, is there any other way to do it? Is this considered secure?
A resource can only set cookies for its host's registrable domain. If Facebook were to use Google Fonts, and Google could use that to override Facebook cookies, that'd be pretty disastrous.
As for where this is defined, step 5 and 6 of https://www.rfc-editor.org/rfc/rfc6265#section-5.3 handle this. (Fetch largely defers to this RFC when it comes to interpreting the Set-Cookie header on responses.)

WSO2 API Manager Refused to set unsafe header "Cookie"

i'm using wso2 api manager(version 2.1.0) to expose some rest api. i need to send "Cookie" as header to some of my rest api(s). I use "API Manager store" to test rest api (https://localhost:9443/store) . but when i set Cookie as Header Request i see this log in browser and call failed :
Refused to set unsafe header "Cookie"
but when i use any other headers like "customHeader" it works fine.
in API_HOME/repository/conf/api-manager.xml , i change this line :
<Access-Control-Allow-Headers>Cookie,customHeader,authorization,Access-Control-Allow-Origin,Content-Type,SOAPA</Access-Control-Allow-Headers>
I also enable "Enable API based CORS Configuration" in api manager publisher (https://localhost:9443/publisher)
I really stuck in this.
is there any way to set Cookie header in api manager?
Thanks in advance
Actually you can't set Cookie header that way.
Browsers restrict the way you create cookies allowing you to set a cookie only for a specific domain and path and with a specific expiration time.
Cookie header is a set of all headers defined to the request domain and path, so you cannot directly overwrite this header.
Setting an HTTP Cookie involves sending Set-Cookie header with the values you want to set.
Check this out:
5.4. The Cookie Header
4.1. Set-Cookie
HTTP cookies explained

Set-Cookie for a login system

I've run into a few problems with setting cookies, and based on the reading I've done, this should work, so I'm probably missing something important.
This situation:
Previously I received responses from my API and used JavaScript to save them as cookies, but then I found that using the set-cookie response header is more secure in a lot of situations.
I have 2 cookies: "nuser" (contains a username) and key (contains a session key). nuser shouldn't be httpOnly so that JavaScript can access it. Key should be httpOnly to prevent rogue scripts from stealing a user's session. Also, any request from the client to my API should contain the cookies.
The log-in request
Here's my current implementation: I make a request to my login api at localhost:8080/login/login (keep in mind that the web-client is hosted on localhost:80, but based on what I've read, port numbers shouldn't matter for cookies)
First the web-browser will make an OPTIONS request to confirm that all the headers are allowed. I've made sure that the server response includes access-control-allow-credentials to alert the browser that it's okay to store cookies.
Once it's received the OPTIONS request, the browser makes the actual POST request to the login API. It sends back the set-cookie header and everything looks good at this point.
The Problems
This set-up yields 2 problems. Firstly, though the nuser cookie is not httpOnly, I don't seem to be able to access it via JavaScript. I'm able to see nuser in my browser's cookie option menu, but document.cookie yeilds "".
Secondly, the browser seems to only place the Cookie request header in requests to the exact same API (the login API):
But, if I do a request to a different API that's still on my localhost server, the cookie header isn't present:
Oh, and this returns a 406 just because my server is currently configured to do that if the user isn't validated. I know that this should probably be 403, but the thing to focus on in this image is the fact that the "cookie" header isn't included among the request headers.
So, I've explained my implementation based on my current understanding of cookies, but I'm obviously missing something. Posting exactly what the request and response headers should look like for each task would be greatly appreciated. Thanks.
Okay, still not exactly what was causing the problem with this specific case, but I updated my localhost:80 server to accept api requests, then do a subsequent request to localhost:8080 to get the proper information. Because the set-cookie header is being set by localhost:80 (the client's origin), everything worked fine. From my reading before, I thought that ports didn't matter, but apparently they do.

AngularJS and Laravel - crossdomain CORS / XHR requests lacking (remember_) cookies

My CORS / XHR requests lacking the remember_xyz cookie in the request headers when i don't use the --disable-web-security option in chrome. If i enable that option the remember_xyz cookie will be included in the request headers and everything is working fine.
As workaround i'm currently sending the auth credentials via basic auth header. But i think that's not the intended or right way.
How can i get that remember cookie included in the request headers?
Edit:
In chrome's network console i can see the following:
(without --disable-web-security option in chrome)
The remember cookie is sent by laravel in the first response headers. But is not included in the next request's headers by angular. Why?
Every request has that OPTIONS preflight request before the actual request fires. Is it possible that the preflight request removes/breaks the cookie somehow?
(with --disable-web-security option in chrome)
The remember cookie is sent by laravel in the first response headers and will be sent in the next request's headers by angular. Everything is fine.
Edit 2:
Is it up to me to include the said cookie out of the response headers into the request headers? When yes, why i don't have to do this with "--disable-web-security" option enabled in chrome?
What i'm doing wrong?
Thank you!
Not sure I'm answering your question directly, but I'll take a stab. You DO need to set certain headers on the client side AND server for CORS.
The client needs to know to send the Cookie headers, or it will strip them out. For jQuery, this means setting the withCredentials parameter in your ajax call. See more info here. This sounds like the issue you are grappling with.
On the server side, you may need to ensure pre-flight requests are setup.
For instance, when I used CORS in Laravel 4, I had a filter to add some headers to each response:
App::after(function($request, $response)
{
// Note that you cannot use wildcard domains when doing CORS with Authorization!
$response->headers->set('Access-Control-Allow-Origin', 'http://dev.domain.local');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', 'Authorization, X-Requested-With');
});
Within a controller, I also had an OPTIONS request respond for pre-flight requests. An example of that is:
public function optionsComplex()
{
$response = Response::make(null, 200);
$response->headers->set('Allow', 'GET, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Methods', 'GET, PUT, DELETE');
return $response;
}
Hope that helps.