Express NodeJs cookie doesn't expire - node.js

I am using Express4 to develop a web app(a simple twitter).
I use npm package "express-session" to manage session and cookie.
But I did not set cookie.maxAge. Based on the git document we have:
By default cookie.maxAge is null, meaning no "expires" parameter is set so the cookie becomes a browser-session cookie. When the user closes the browser the cookie (and session) will be removed.
but actually, when I close my chrome and start it again, I still have the same cookie generated by server in last request.
Has anyone faced same problem? Thanks for help.

You can try:
// This user should log in again after restarting the browser
req.session.cookie.expires = false;
Each session has a unique cookie object accompany it. This allows
you to alter the session cookie per visitor. For example we can
set req.session.cookie.expires to false to enable the cookie
to remain for only the duration of the user-agent.

Related

Express session, how do I get the session after posting? I see the session ID in browser under cookies, but it's undefined in request object?

Sorry guys, I'm really new to sessions and cookies and I'm trying to understand the mechanism behind it. I wanted to add register/login to my simple website and in order to do I need to understand web authentication and I really think I will have tons of questions regarding this topic.
Initially, I have register page that sends info after clicking submit button to a node server using express.
I'm trying to see what happens, so I've created a session in post route, it's created in the browser (connect.sid), then I commented out the part that creates that session and just tries to redisplay the session object, but it's undefined, but I still can see the session in the browser's cookies section, so what's going on? Thanks
app.use(session({
secret:"my test secret",
cookie:{},
resave:false,
saveUninitialized:false
}))
app.post("/register", (req, res) => {
req.session.usertest = "testsession_hardcodedvaluefornow";
console.log(req.session.usertest); // -> this is okay when above line to create is uncommented
//but when I comment the session assignment, it becomes undefined?
res.send("In register...");
})
I can see the session cookie even after commenting out the create session and posting over and over.
connect.sid s%3A_TahsTv0xhY-iHIdjDRblYJ_aZZ5oiSd.do7JcOGR1FaXPcFFIQ6hg5AW%2B0XVsYwIRO8vndyjDzs
req.session.id produces a different value (not undefined) even if I delete my session in the browser, so not sure where that comes from.
There is no "usertest" key in the session object, therefore it is undefined. The reason it's not undefined when you uncomment that line is because you create that key yourself in that instant with that line.
You can get the whole session object by using req.session, the session id by using req.session.id and the session cookie by using req.session.cookie.
Edit
To further clarify: a session will be made for every connected client. That is why you can see the cookie in the browser. That has no meaning however, it's just a way to uniquely identify that client (without actually telling you who that client is). Any information about that session (whether they're logged in, user id,...) needs to be stored in a session store. Express-session will use memory store by default, if the server restarts all that information will be lost, which is why that key doesn't exist. In order to preserve that information it has to be stored in a persistent session store. More information on session store implementations for express-session and how to use them can be found here: https://www.npmjs.com/package/express-session
As for the cookie values you get, those are the default ones set by express-session since you haven't set any yourself. You can change the maxAge to let it expire (or set it so 10 years or more for a more persistent session), you can specify a domain to which that cookie belongs, you can set it to secure (to only allow it over secure connections, e.g. https) and httpOpnly is by default true. httpOnly cookies cannot be accessed/altered by the client (although you can see them in the browser), do not set this to false.

SameSite Cookie attribute issue

I have a web application with react in front-end and node in backend.
I am using passport authentication with passport-saml strategy. Since the last browser update i am seeing an issue. Once I try to login I was taken to the authentication page and it returned back to app page again, then auth page and this continues. looks like i was in a redirection loop.
Once I disabled the samesite attribute flag in chrome then the issue got resolved.
I read some articles and realized that the samesite attribute is causing this. (please correct me if i am wrong. Also want to know), where we will be adding this in backend.. I was using node express session module and addded a cookie object as :-
cookie: {sameSite: 'none', secure: true}
Can someone please help me to find a solution for this?
Is you application behind proxy server with ssl enabled?
I had a similar problem with similar setup and similar symptoms, but I've already switched from saml to oauth (without using passport), so I'm not sure if this helps you.
Anyway, there were two things I needed to do to keep a session cookie 'alive' over the requests.
Set 'trust proxy' in your server code: app.set('trust proxy', 1)
Set X-Forwarded-Proto header to proxy server config (mine is nginx):
location / {
proxy_set_header X-Forwarded-Proto $scheme;
...
}
I'm not sure this is your case, but I'm assuming your app is deployed (I haven't faced this issue in localhost, so your problem may be somewhere else) and your session is being set.
After 3 days trying to figure It out. I finally found a way around this issue, It's not a fix, I'm quite sure PassportJS will come with a solution for that eventually, but for now It allowed me to get the user from the authentication.
Since we are not being able to get the user from the cookie, but the information is in the server session, the way to get this information is to add to the 'server.js' a route to get the user directly from the server session:
app.get('/api/getUser', (req, res) => {
res.json(req.session.user);
});
For some reason, I suppose the lack of cookie somehow, using the req.session inside of a router is returning undefined, but If used inside 'server.js' (or your server index file) It gets the session.
If you need the req.user._id or some other sensitive information for other requests, I would recommend returning a jwtToken with this information to the frontend (in res.json), then save the token directly in localStorage and pass the token in the body of your requests, is not the ideal, but It's the safer way I could think to keep the ids safe.

Getting Clients Cookies in Node HTTP Server

I am trying to set/get cookies for users that browse on my web server, I found the following StackOverflow question: Get and Set a Single Cookie with Node.js HTTP Server and I was able to get the cookie set on the browser just fine. When I go to the cookie viewer I see the cookie I set just as I want it. The problem comes when I try to view the cookies, the request.headers.cookie is always undefined. How would I go about getting the cookies on a users browser, preferably without NPM modules and purely node and its own modules?
How I'm setting the cookie (this works fine, I am able to see this cookie in the browser when I go to view my cookies):
response.writeHead(statusCode, {
'Set-Cookie': cookie
})
// statusCode = 200
// cookie = 'token=SOME_TOKEN'
// In the browser I see the exact cookie I set
How I'm trying to get the cookie (not working always undefined):
let cookies = request.headers.cookie
// This returns undefined always
// even when I can view the cookie in the
// browser the request is coming from
// Also quick note: I'm currently not
// parsing the cookies out to view them as
// a JSON object because I can not get any
// of the cookies
EDIT:
It seems I have finally found the error, it sets the cookie path to be whatever path I set the cookie on, so I was setting the cookie on the "/auth" route. How can I make it so that this cookie is accessible from any route the user goes to?
Ok I finally found the solution, my error was that it was auto-setting the path of the cookie to be "/auth" so I could only access the cookie if the url requested contained "/auth", where I set the cookie I changed it to the following:
response.writeHead(statusCode, {
'Set-Cookie': cookie + '; Path=/'
})
And now I can access my cookie

ExpressJS session cookie is not updated

I am trying out express.session() middleware. The usage seems to be fairly simple and I quickly implemented what I wanted. Basically I implemented authentication based on session cookies. As a part of this function I implemented checkbox "remember me" which is pretty much a standard for login windows on the web. Here appears to be a problem.
I want the following functionality - when user opens/reloads the page if there is valid session cookie and it matches existing session object on server application, then session.cookie.maxAge on server and cookie expiration on client are reset to the new value (which is now() + x). Therefore making page work like - if user did not come back for e.g. 3 days then he is automatically logged out, but if he comes back within 3 days, then he is logged in and auto-logout counter is reset back to 3 days.
I expected that session.touch() would do it, but it only seems to reset session expiration date on server and doesn't push new cookie to client.
My question - did I miss something or it was intentional implementation?
PS: I could regenerate session each time and that would update cookie. But I concern for overhead of running this code on every request I also could manually push updated cookie, but would prefer to do it within express.session() functionality.
I also found this question which was never answered (except for OP himself):
Updating cookie session in express not registering with browser
"cookie.maxAge" is updated automatically by connect.session touch(), but only on server side.
The updating of maxAge on client side has to be done manually with res.cookie.
Eg.:
res.cookie(
'connect.sid',
req.cookies["connect.sid"],
{
maxAge: req.session.cookie.maxAge,
path: '/',
httpOnly: true
}
);
See this answer to the StackOverflow question you linked to above:
https://stackoverflow.com/a/27609328/4258620
For now Express-session should update cookies in browser, in code .
rolling: true in config provide your desirable functionality. It automatically performs touch on every request. Docs

xpage - sessionID and DomAuthsessId

The domauthsessid cookie is created when a person logs on to domino server. I have also seen a cookie for sessionID when dealing with xpages. Is sessionID specific to xpages? How is this sessionID used by xpages?
Taken from http://www-01.ibm.com/support/docview.wss?uid=swg27021314:
Q. Sometimes when XPage is submitted it adds SessionID to the URL and
some JavaScript stops working. What's that SessionID?
A. This is due to the way HTTP is working. HTTP is stateless so the
browser must pass an ID to the server in order to keep a session open
on the server. There are two ways for passing this ID.
1 - Passing the ID as part of the URL
2 - Passing the ID as part of the cookie from the browser
The second way is the preferred way. But for the first page the XPages
engine doesn't know if the browser that is connecting to the page is
supporting cookies or not, so it tries first by passing an ID and a
cookie. And on the second request it looks for the cookie, and if the
cookie is there it removes the ID from the URL. So if you look at all
the application servers they are all working like that. Now there is a
property in XPages that says 'assume that the client has cookie', and
in these cases do not use a session ID at all. So that would break
some browsers that do not support having cookies enabled.
The sessionID URL parameter is not used with Lotus Domino 8.5.3 - only with 8.5.2 and older.
Create a Xpage as the following:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core"
rendered="false"
>
<xp:this.beforeRenderResponse><![CDATA[#{javascript:
var externalContext = facesContext.getExternalContext();
var request = externalContext.getRequest();
var response = externalContext.getResponse();
var currentContext = com.ibm.domino.xsp.module.nsf.NotesContext.getCurrent();
var session = request.getSession(false);
var sessionId = session.getId();
// flush the cookies and invalidate the HTTP session...
for(var cookie in request.getCookies()){
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
session.invalidate();
// now nuke the XSP session from RAM, then jump to logout...
currentContext.getModule().removeSession(sessionId);
externalContext.redirect("?logout");
}]]></xp:this.beforeRenderResponse>
</xp:view>
and then create a link or Page Link to point to the above Xpage…
This will log you out and remove ALL cookies.
DISCLAIMER: code found on the net (kudos to that person) and this will not work for client certificate authenticated servers…
Why paste this answer so late in the discussion? Because I've looked for the answer and none of the above is working so for future references…
The sessionID cookie is used by XPages so that the server knows which session it dealing with so when you run some code like sessionScope.get(param) it knows which user's sessionScope to look at.
In addition, a session represented with sessionId should not be confused with session-based authentication.
domauthsessid cookie is used in single-server authentication. If you are using multi-server authentication, LtpaToken will be used for that purpose. This cookies persist your authentication session.
XPages session will be preserved when you login, logout or even login with a different user. An XPages session will only be deleted after a specific idle time whereas authentication session is deleted when you logged out.
The cookie manages the browser session for the server. If you do a ?logout, the sessionScope variables are not removed. You can use SSJS to clear the sessionScope map and logout, but that will only clear the map for the current NSF. If you remove the sessionID cookie, the XPages session is removed and all sessionScope variables for the whole server are removed. I added an snippet to the xSnippets OpenNTF site that does the logout and remove sessionID cookie.
Mikael Andersson Wigander shows us a nice solution how to logout from a Domino server. However, the ?logout parameter in the URL isn't always working.
We found out that the logout page from Mikael only logged out a user in the first attempt. The browser then caches this logout page and prevents the user from logging out the next attempt.
The following change of Mikael's solution will tackle this problem:
var appUrl = facesContext.getExternalContext().getRequest().getContextPath();
var url = appUrl +"?Logout&t=" + new Date().getTime() + "&redirectto=" + appUrl ;
facesContext.getExternalContext().redirect(url);
Call the Xpage using a parameter also containing the time in milliseconds:
<xe:this.href><![CDATA[#{javascript:"Logout.xsp?" + new Date().getTime();}]]></xe:this.href>
Now the user will be able to log out every attempt.

Resources