How to expires session when browser is close in passport.js - node.js

I want to expire session when the browser is closed.
I'm using res.cookie('testlocale', 'en', { maxAge: 900000, httpOnly: true });
Also which event should i use in front end(onbeforeunload or onunlod)
I'm not able to understand how to do this. I'm using handlebars in front-end

If you use express-session.
You can set expires: false.
req.session.cookie
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.
From docs
If you want to manually delete cookies on frontend, I think both are good fit. But I'm not sure it's good idea.

Related

Set persistent cookie with Express.js

How can I set a cookie that is not removed when the browser is closed?
The docs of res.cookie show option parameters you can pass to the method but I haven't been able to find a configuration that makes the cookie persist after closing the browser.
res.cookie('name', 'spence', { expires: 0 });
Simply set the expires parameter to some value in the future and the cookie will persist. I was getting hung up in the docs because what I thought I wanted was a "session cookie" but like its name implies, a session cookie only lasts for the duration of the browser session.
While it isn't possible to have a cookie to persist indefinitely, you can essentially do the same thing by setting the cookie to expire on some date far in the future.
var farFuture = new Date(new Date().getTime() + (1000*60*60*24*365*10)); // ~10y
res.cookie('name', 'spence', { expires: farFuture });

express-session secure: true

app.use(session({
secret: "testing credentials",
store: sessionStore,
resave: true,
saveUninitialized: true,
cookie : {
httpOnly: true,
//secure: true,
maxAge : 60 * 60 * 1000
}
}));
I'm working on some security problems on my newly developed website. And after done some research online, if secure=true is set, then it will be more secure. However,
If set secure: true, then information inside session will lose every time when the user send another request. Is there a way to solve this problem? If doesn't include "secure: true" in the cookie: , then the session will last for that maxAge.
If a cookie is set with the secure flag, it will only be sent to the server by the browser over https, and not plain http. This should be the default for production environments.
However, when developing an app, you probably use plain http on your dev machine. If you set your session cookie as secure in this case (using plain http), the server will never receive it, and you will experience a new empty session on each request.
So in short, you should only set the cookie as secure if you are using https (that is, in later stages of your development pipeline, and definitely in production).
On another note, if you set maxAge, the cookie will be persisted, which is not the best practice for session cookies. Without maxAge, the cookie will be kept until the user closes the browser and not normally persisted to disk, which is the correct behaviour for session cookies.

is it reasonable to get sessionid from url other than cookie? something about express-session

I have some domain( maybe change very frequently), and two stable domain(e.g. auth.aaa.com, api.aaa.com).
Since express-session(https://www.npmjs.com/package/express-session) default get sessionid from cookie, but when crossing domain,ajax won't send cookie( I don't want to use something like Access-Control-Allow-Credentials ).
I want to add the sessionid to the querystring, and forge a cookie before express-session middleware.
app.use(function(req,res,next){
var ss = req.query.ss;
if(ss){
var signature = require('cookie-signature');
var cookie = require('cookie');
var signed = 's:' + signature.sign(ss, "secret");
var data = cookie.serialize('jsessionids', signed);
req.headers.cookie = data;
}
next();
})
app.use(session({
name:'jsessionids',
store: new redisStore({
host:config.redis.host,
port:config.redis.port,
pass : config.redis.password,
db: config.redis.database
}),
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'secret'
}));
is it reasonable? or any suggestion else?
It is generally not advisable to add the session as a query parameter, you have to jump through lots of hoops to get them to near the same level of security as cookies.
The main problem is that it is much more vulnerable to session fixation or session hijacking, which is where an attacker can steal and use another user's session.
Some key points to take into consideration
Query parameters are stored in browser history, bookmarks and referrer headers (just to name a few) which
could allow an attacker to use another users session on a shared
environment. Query string based sessions are much easier to leak outside their intended scope.
Cookies have better security mechanisms built in such as the
httpOnly flag which makes the cookies in-accessible to JavaScript
(whereas query strings are always accessible). The secure flag makes
sure that cookies are only sent over a secure connection (You could
perhaps use HSTS to help guard against MITM attacks for query string).
A user who share a link with their sessionID in the query string
which would allow any other user to assume their identity.
If you do decide to use the sessionID in the query string make sure you set an expiration time for the session and always to use TLS to securely transmit the session (same applies to any authentiction method).
Saying that, If you can avoid using query string based sessions, I would advise you do.

What is the difference between cookies maxAge and expiry

I'm on NodeJS, Express app i am using cookies for some features of my app. I need to set cookie life to one month.
For this very purpose i've set cookie maxAge to days*hoursPerDay*minutesPerHour*secondsPerMinute*1000 to achieve one month time 30*24*60*60*1000 = 2592000000.
Yet in browser expiry of my cookies is near 10 hours.
What am i missing, my calculations are wrong? or I am using wrong attribute(maxAge)?
Also what is the difference between maxAge and expiry attribute of cookies?
As far as i know, maxAge wont save in cookie's specifications.
As Don't trust Cookie setMaxAge demonstrated, The mechanism of maxAge works like Change/manipulate expiration date of cookie (based on SERVER_SIDE) but browser checks cookie's expiration date, based on CLIENT_SIDE.
From my point of view, This is misbehavior. Because in order to make max-age work as expected, both client/server DateTime should be synchronized.
maxAge should be set in milliseconds ( i was wrong, as i referred to client part)
https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
are you setting coolie like below?
res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
http://expressjs.com/api.html#res.cookie

Why is there a cookie in the req.session in node express?

It's more for my understanding. Why is there a cookie object in the req.session in express?
I use req.session to store the login status and username.
The cookie object in req.session is the same as the cookie properties in the client cookie, placed by express.parseCookie but without sessionID.
Can anyone explain why this is in there?
It cant be for the purpose to identify cookie and session because thats already made by the cookie value and the session ID (req.session.ID), or am I'm wrong?
- req.session -->
{ cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
loggedIn: true,
username: 'luidpold' }
For convenience. It’s the cookie associated with the session, and you can query/modify it.
The session handler in Express comes from Connect. The documentation for Connect says:
Session#cookie
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.
Session#maxAge
Alternatively req.session.cookie.maxAge will return the time remaining
in milliseconds, which we may also re-assign a new value to adjust the
.expires property appropriately.

Resources