How to make a cookie available to all paths in a domain? - cookies

I created a cookie in a java filter and added back to the response
response.addCookie()
before returning to the client node.js application. This web application is accessed using a localhost URL in the browser. After reading about cookie domain issue while using 'localhost', i did not set any domain or path in the cookie, while creating it.
Now the Chrome or Firefox browsers don't show-up the cookie in the browser. All my URLs are http://localhost but, each page having different path.
Step 1: During a request to http://localhost/app/login cookie is created and set in the response
Step 2: When the page loads after response, no cookies are shown in Chrome
Step 3: During the next request http://localhost/app/customer the previously created cookie is not recieved when trying request.getCookies().
Step 4: Before returning back to client application, a cookie is created
Step 5: Now the cookie created in Step 4 is shown in Chrome
Step 6: The next request is also sent to http://localhost/app/customer , now the cookie created in step 4 is recieved in the server as well
If cookie creation for localhost is an issue, how does it work for Steps 4-6 only ?
How can i make the created cookie available to all paths under the
localhost domain ? I tried using cookie.addPath("/") but, no change.
Note: Due to admin privilege issues in my development machine, i am not able to set-up a domain name to my localhost IP in etc/hosts file.

In your Java server, you should call cookie.setPath("/") before adding it to response.
Such cookie will match all request URIs. It's a pity that it is not the default behavior.
I have a more detailed explanation of cookie path here - http://bayou.io/release/0.9/javadoc/bayou/http/Cookie.html#path

Not sure path is the issue. Path does not affect whether a cookie is created; it only determines whether it is presented. If cookies aren't showing up in the browser's cookie jar they are being rejected for some reason other than path.
Chrome will not accept cookies for localhost because it does not accept cookies in the top level domain. The domain in the URL has to have a dot in it somewhere. So you could either add a hosts entry (recommended) or just trying using 127.0.0.1 instead of localhost.
Also, none of this will work if the cookie is marked as secure or is being set with a domain attribute. If either of those is the case, you MUST use a hosts entry instead of localhost or 127.0.0.1.

Related

Keystone session cookie only working on localhost

Edit:
After investigating this further, it seems cookies are sent correctly on most API requests. However something happens in the specific request that checks if the user is logged in and it always returns null. When refreshing the browser a successful preflight request is sent and nothing else, even though there is a session and a valid session cookie.
Original question:
I have a NextJS frontend authenticating against a Keystone backend.
When running on localhost, I can log in and then refresh the browser without getting logged out, i.e. the browser reads the cookie correctly.
When the application is deployed on an external server, I can still log in, but when refreshing the browser it seems no cookie is found and it is as if I'm logged out. However if I then go to the Keystone admin UI, I am still logged in.
In the browser settings, I can see that for localhost there is a "keystonejs-session" cookie being created. This is not the case for the external server.
Here are the session settings from the Keystone config file.
The value of process.env.DOMAIN on the external server would be for example example.com when Keystone is deployed to admin.example.com. I have also tried .example.com, with a leading dot, with the same result. (I believe the leading dot is ignored in newer specifications.)
const sessionConfig = {
maxAge: 60 * 60 * 24 * 30,
secret: process.env.COOKIE_SECRET,
sameSite: 'lax',
secure: true,
domain: process.env.DOMAIN,
path: "/",
};
const session = statelessSessions(sessionConfig);
(The session object is then passed to the config function from #keystone-6/core.)
Current workaround:
I'm currently using a workaround which involves routing all API requests to '/api/graphql' and rewriting that request to the real URL using Next's own rewrites. Someone recommended this might work and it does, sort of. When refreshing the browser window the application is still in a logged-out state, but after a second or two the session is validated.
To use this workaround, add the following rewrite directive to next.config.js
rewrites: () => [
{
source: '/api/graphql',
destination:
process.env.NODE_ENV === 'development'
? `http://localhost:3000/api/graphql`
: process.env.NEXT_PUBLIC_BACKEND_ENDPOINT,
},
],
Then make sure you use this URL for queries. In my case that's the URL I feed to createUploadLink().
This workaround still means constant error messages in the logs since relative URLs are not supposed to work. I would love to see a proper solution!
It's hard to know what's happening for sure without knowing more about your setup. Inspecting the requests and responses your browser is making may help figure this out. Look in the "network" tab in your browser dev tools. When you make make the request to sign in, you should see the cookie being set in the headers of the response.
Some educated guesses:
Are you accessing your external server over HTTPS?
They Keystone docs for the session API mention that, when setting secure to true...
[...] the cookie is only sent to the server when a request is made with the https: scheme (except on localhost)
So, if you're running your deployed env over plain HTTP, the cookie is never set, creating the behaviour you're describing. Somewhat confusingly, in development the flag is ignored, allowing it to work.
A similar thing can happen if you're deploying behind a proxy, like nginx:
In this scenario, a lot of people choose to have the proxy terminate the TLS connection, so requests are forwarded to the backend over HTTP (but on a private network, so still relatively secure). In that case, you need to do two things:
Ensure the proxy is configured to forward the X-Forwarded-Proto header, which informs the backend which protocol was used originally request
Tell express to trust what the proxy is saying by configuring the trust proxy setting
I did a write up of this proxy issue a while back. It's for Keystone 5 (so some of the details are off) but, if you're using a reverse proxy, most of it's still relevant.
Update
From Simons comment, the above guesses missed the mark 😭 but I'll leave them here in case they help others.
Since posting about this issue a month ago I was actually able to work around it by routing API requests via a relative path like '/api/graphql' and then forwarding that request to the real API on a separate subdomain. For some mysterious reason it works this way.
This is starting to sound like a CORS or issue
If you want to serve your front end from a different origin (domain) than the API, the API needs to return a specific header to allow this. Read up on CORS and the Access-Control-Allow-Origin header. You can configure this setting the cors option in the Keystone server config which Keystone uses to configure the cors package.
Alternatively, the solution of proxying API requests via the Next app should also work. It's not obvious to me why your proxying "workaround" is experiencing problems.

JMeter 5.4.1 Cookie Manager - User-Defined Cookie not added to request's cookies

Firstly, I did add the line CookieManager.check.cookies=false to jmeter.properties.
What I'm Trying to Do
I want to add a cookie to a request's existing cookies.
For example, I see the request has [edited]:
Cookie Data:
c1=sfasfsfsfsfs; c2=erqwerqwrr; c3=poiuopiupoi
Expected Results
I would like it to have:
Cookie Data:
c1=sfasfsfsfsfs; c2=erqwerqwrr; c3=poiuopiupoi; partner=favicon.ico
Here is what I tried:
BASE_URL_2 is a variable defined in the form qa.company.com.
Actual Results
Whatever I have tried so far has not made any change in the cookies.
What else shall I try?
Underlying Motivation
Recorded a Web session and played it back.
Added a RegEx Extractor to pull out a token and then added it to subsequent requests. That helped.
However, certain requests failed with an custom application exception Security violation, please refresh.
Probably session login state is not being passed, so the website thinks the call is "stale".
I've seen this on the GUI when the session expires and you try to click a button on the site.
On comparing the cookies seem in JMeter with what I saw in the Chrome Debugger, it was clear that there were more cookies in the running application than what I had in JMeter.
Are you sure you're using HTTPS protocol because if you have secure flag and using HTTP protocol - the cookie will not be sent.
Also remove = from partner= otherwise you will end up with partner==favicon.ico
Demo:
More information:
Using HTTP cookies
HTTP Cookie Manager Advanced Usage - A Guide

CookieManager.check.cookies=false not working

I jmeter.properties I set "CookieManager.check.cookies=false" but cross domain cookies still aren't working.
For example going this guide and using their demo site setting a cookie with a domain of "blazedemo.com" works, but if I change the domain to anything else it fails.
JMeter sends only cookies that match the domain of server in the request.
The property you've set impact the way JMeter read cookies not the way it writes them.
To check, emit a http request towards one host for which you created the cookie, you'll see it works.

Logged out of one spring app when using two spring boot apps at the same time

I have two spring boot applications.
module1 running on port 8080
module2 running on port 9090
I have set the ports using this property in application.properties file
server.port=${port:9090}
Both modules have /login, /signup which are accessible without authentication accomplished via the code below.
http.authorizeRequests()
.antMatchers("/signup", "/login").permitAll()
Any other request requires that the user be authenticated.
If i use one module at a time there is no problem,
But if try to use them back and forth at the same time then the problem is that i have to login again to the previous app every time i use the other one.
Eg.
Goto Login page to module1 - (Header response has set jsessionid=XX) ok
Login to module1 - ok
Browse secured content on module1 - ok
Goto Sign Up page on module2 - (Header response has set jsessionid=YY) ok
Try to browse to another secured content on module1 - I have to login again
I'm quite sure it's due to the jessionid being reset by module2.
Are HTTP cookies port specific?
I have read this article which states that cookies are not port specific.
But there must be a solution so that i don't have to login everytime i switch apps.
You need to use different cookie names for the two applications.
There are different ways to do these, the most simple one, for a spring-boot application with version >=1.3 is just setting a property :
server.session.cookie.name = MYSESSIONID
Other ways are described in this post .
Map your applications to different context paths, so the JSESSIONID cookies will be independent; otherwise, the cookie is for the same context, so there is effectively one cookie for both applications. Another solution would be to use different hosts.
Please note that you don't only change context path of the cookie here: if you change context path of your application, Servlet API implementation will handle cookie context path change for you.
I've experimented a bit with same host and different context paths.
I'm currently having two applications launched, both have Servlet API as their base (and JSESSIONID cookie is defined by Servlet API's session mechanics). The applications both run on localhost, on different ports, and with different contexts (/app1 and /app2). I've logged into both applications, and in Chrome's dialog which lists cookies I can see two JSESSIONID cookies: one for localhost and /app1 and another for localhost and /app2.
Then I logout in /app2. Its JSESSIONID is destroyed and recreated with different content (because I've been redirected to the login page again). (Please note that to see that change I had to close Cookies dialog and reopen it as Chrome did not update it on the fly). At the same time, JSESSIONID cookie which belongs to /app1 is intact, and I can proceed working in /app1 (so I was not logged out from it).
UPDATE
One more experiment. I've mapped both appilcation at the same context (/app1). They run on localhost:8084 and localhost:8085. I do the following:
I log into the first application (port 8084)
I log into the second application (port 8085)
I switch back to the first application tab, click any link and see that the session is destroyed (as I am being redirected to login page).
So even if applications run on different ports of the same host with the same context path, they use the same cookie. Basically, this is what was said in Are HTTP cookies port specific? : Cookies do not provide isolation by port
A little summary:
Different hosts: no problem, cookies are different
Different application contexts: no problem, cookies are different
Same host, same application context, different ports: there is only one cookie, and this causes a conflict.
So the recipe is the same as before:
Either use different hosts (that is host names, not including port)
Or use different context paths
Or (as another answer suggests) change cookie name to avoid the conflict

How to stop domain cookies being used for subdomains?

I have a setup with the following domains:
mydomain.com
www.mydomain.com
There is one problem (tested on Internet Explorer):
if some cookie is set for mydomain.com, this cookie is also effective for www.mydomain.com even if I set a cookie with the same name for www.mydomain.com.
More specific examople:
1) the user chooses his prefered language on website mydomain.com and I set the cookie usrlng=en
2) next day someone else uses the same computer, naviagtes to www.mydomain.com and chooses his language, and I set the usrlng=de. But Internet Explorer keeps sending both cookies usrlng=en and usrlng=de to the server (I see this in Fiddler)! Why is it sending the same cookie twice and not overriding 'usrlng' with the subdomain value?
At the same time I see that PHPSESSID is being overwritten correctly for the subdomain, there are no two PHPSESSID cookies being sent to the server.
How can I fix the usrlng cookie and make it work the same way as PHPSESSID works?
You can also set a different save_path for each... so they don't share the sessions.
PHP example:
$subdomain = array_shift(explode('.',$_SERVER['HTTP_HOST']));
ini_set('session.save_path','D:\website_sessions\'.$subdomain.'\');
ini_set('session.save_path','D:\website_sessions\'.$subdomain.'\');
PHP needs access to write in the sessions directory.
For now I solved the problem by setting the 'host' of the cookie instead of 'domain'; 'host' property allowed to limit the cookie to mydomain.com or www.mydomain.com.
Maybe that is the only way to go and 'domain' cannot be set up to oveeride top level domain cookies.