Node session cookie that expires - node.js

Is it possible to create a session cookie (one that is automatically deleted when the browser closes) AND also has an expiration so that it will expire after a set time, let's say 15 minutes unless the user continues using the site? If they use the site, i'd like to reset the expiration so it lasts another 15 minutes.
I've only really had luck with either creating a session cookie that expires when the browser is closed OR stays around as a persistent cookie but has an expiration either using expires or maxAge arguments.
The only thing I can think of is to create a session cookie that has a timestamp value stored in it and in the session middleware, check of the current time > the timestamp value and then deny the request and delete the cookie by setting it to null. If current time is <= the timestamp updating the timestamp to the new date effectively extending the session timeout.
While my idea may work, it makes me think there is a more official way of accomplishing what I want.
I'm currently experimenting with node and express so any insight that is tailored for that build-out would be appreciated.

Because the way you create a session cookie is to leave out the expiration, you can't really do it with a single cookie.
But, you can do it with two cookies, one session cookie and one expiring cookie. Here's some logic for doing it with two cookies:
Create a random number.
Create a session cookie such as session=randomNumber.
Create a second cookie expiry=randomNumber that expires in 15 minutes.
Have your code check to see that both cookies exist and contain the same random number.
If the browser is closed, the session cookie will be deleted.
If 15 minutes passes, the second cookie will be deleted.
If the browser is closed and then reopened, there won't be a session cookie and even if you coin another one, the second cookie won't have the same random number in it.
By checking for the presence of both cookies, you're making sure that both conditions have been met.
And, if you want the 15 minute cookie to continually refresh itself on any page load, you can have your server recreate that cookie on each page load with a new fresh time 15 minutes from now.

Related

Sails.js expire session at given time or every end of day

TLDR version: I wanted the session in sails to expire at a specific given time or date or end of day.
I gave up trying to figure out how to expire a session in sails/node at a given time.
the cookie.maxAge option in the sessions.js seems to be updating the TTL of the session of the key in redis on a given millisecond. So I tried setting each maxAge by running
req.session.cookie.maxAge = Utility.getEndOfDayMilliseconds();
req.session.save();
I created a utility that gets the value of the milliseconds from the current time to end of day.
It works when I am idle in one screen, but when I navigate on pages, the TTL on a session key in redis gets refreshed every pag navigation and the maxAge gets back to the originalMaxAge. I don't wan't that to happen.
How does one do this? The cookie that is set in my browser is correct but I can change the expire value at a future date so that my session does not expire and keep on refresh a page so that the TTL will refresh.
Thanks!
you may find an answer in the official Sails website documentation > concepts > sessions.

How to keep user always logged in without infinite session

Wondering how this is typically implemented. Examples of always logged in websites are StackOverflow, Facebook, and Twitter. It seems like you'd have to have a background job regenerating the session ID (assuming you store session by ID in a database) before the session expires (say you tell the cookie to expire in 5 minutes). So every 5 minutes every session would be regenerated to keep it logged in while also keeping it secure. But before going down that road I'd like to know if this is how others implement it or if there is a more standard approach.
As far as I know, this is how it is done in majority of websites.
A cookie is set with an access token and limited life(of course, if the user checks on'Keep me logged in'). If the user comes to visit the site within that timespan, he is logged in and a current session is generated(from the server). And, the cookie timespan is reinitialized to the pre-decided time.
Say for example: I log in to a website example.com and check its check box, to keep me logged in. Now, as soon as I click the login button and and validated by the server, the server generates a session(for current session) and a cookie(for future sessions), with a time limit of say 1 month. Now, If i come back on say 29th day and open example.com, I shall automatically logged in using the token set in the cookie. The cookie will send my info to the server and the server shall generate my current session. Most importantly, the server will reset the cookie to expire after one month.
If, I return to the website after 30 days, then the cookie will either force me to login again.
I hope my input would be of some help to you.

How to detect the end of a user's session on website to delete session token

For user's who do not want to be remembered between sessions on my site I generate a temporary session token and send it as a cookie to the client so they are remembered between webpages on my site.
The cookie automatically expires at the end of the session since that is the default, but how can I detect the end of the session server side?
I want to delete the session token at the end of the user's session from my database and then should they log in again I want to generate a new session token.
The "session" concept in "cookie-expires-at-end-of-session" is actually only known on the browser. From wikipedia:
A session cookie, also known as an in-memory cookie or transient
cookie, exists only in temporary memory while the user navigates the
website.[13] Web browsers normally delete session cookies when the
user closes the browser.
So this might still leave a cookie to linger quite a long time if the user keeps his browser open for days in a row (like me).
One way to achieve what you want is to have the web page send a "heart-beat" to the server, e.g. using setTimeout in javascript to access a certain URL every 10 seconds, and passing some unique identification of his "session" (in the sense that you want, not the cookie-session). If that heartbeat stops, you know your web page was closed, or the user surfed away from it etc, and you can immediately clean up your server side state.
More in detail, the "heartbeat URL" would simply maintain a list of active sessions. Each access to that URL would update the time-stamp of last activity of the specified session (e.g. http://..../heartbeat?id=12345). That way you have a list of "most recent time stamps" for all active sessions. A separate cleanup thread would then run over that list once in a while to clean up those sessions that haven't been updated in the last (10...) seconds.
For example (using JQuery for the URL access, could do the same with just XMLHttpRequest...)
<script>
function heartBeat() {
setTimeout(function(){
$.get("heartBeat?id="+mySessionId, function( data ) {
// you may want to add sanity checks here, e.g. what with invalid session ids?
heartBeat(); // next call to heartBeat after OK response
}
}, 10000);
}
heartBeat(); // first call to heartBeat
</script>
This will call your server URL every 10 seconds (plus your server response delay).

What's exactly the meaning of "saveUninitialized","resave" and "rolling" properties in express-session?

Recently,I'm learning about the middleware "express-session" of express, I want to understand all properties in the given options.But when I read about the API of express-session, I'm confused with the three
properties:saveUninitialized, resave and rolling.
They all have an effect on cookie setting or session operation, so what's the difference and connection of them?
Hope somebody can help me to distinguish them,
Thanks a lot!
When a modern browser makes a request, it appends all cookies that match the current domain (website) in the Cookie header. Here's an example of what my browser might send if I visit stackoverflow.com:
Cookie: acct=1234
No cookies are sent by the browser when you visit a site for the first time. In that case (and if the owner wanted to utilise cookies to track user sessions, for example) the server will commonly respond with a Set-Cookie header, something like this:
Set-Cookie: acct=5678; expires=Sat, 15 May 2050 15:32:57 GMT; domain=.stackoverflow.com
(It can also append path, secure, and HttpOnly options, all explained here) I'm simplifying but, by default, express-session only sends Set-Cookie when you visit a site for the first time.
If rolling is true, it will be sent every time. This has the desired side-effect of continuously rolling forward the expiration of the cookie with every page refresh. The new expiration date is determined by adding maxAge to the current server time.
If you alter the req.session object, it will be saved back to the session store at the end of the request; otherwise it will not be saved. Setting resave to true forces it to be saved everytime, even if no changes were made. It might seem illogical but certain stores might require this (although, having looked through the list, it seems that none currently do).
When a cookie is set for the first time, a new session object is created in memory and saved to the store at the end of the request. This can take up a lot of space in the db if you have many people visiting and then bouncing without performing any meaningful action like logging in. You can choose to only save sessions if they deviate from the default session object (ie. if you've modified it, like setting req.session.user = user; on login) by setting saveUninitialized to false.
Something to be aware of is certain combinations of these values (along with others) might produce unexpected behaviour. For example, the documentation states:
When this option [rolling] is set to true but the saveUninitialized option is set to false, the cookie will not be set on a response with an uninitialized session.

Persistent cookie normal timeout behaviour

Im implementing a persistent cookie based on http://jaspan.com/improved_persistent_login_cookie_best_practice.
Question :
If a user tries to access a page. After the authentication is successful, the used token is removed from the database. A new token is generated, stored in database with the username and the same series identifier, and a new login cookie containing all three is issued to the user.
When you generate a new cookie here, you need a cookie age, I put it as default of 1 month. So, every time the new cookie is generated, should I just put it as default(1 month) or should I store a field in my db which counts the expiry time(something like 1 month countdown). Whats the normal behaviour here ?
Another question, I feel that it is a bit overkill to remove the token and gerenate a new token to db everytime you visit a page. Is this operation as costly as I thought?
Add the expiry both server and client-side, otherwise a cookie grabbed by an attacker would be valid forever.
Changing the token is good and can help protect against the above scenario. Every page visit seems a bit excessive, and could have a performance impact if your site gets busy. How about refreshing it every 5 minutes or so?

Resources