Session timeout issues - javascript

If there is a timeout set on one of our pages, and that same page is opened in another window/tab, is there a way to destroy/stop the timeout in the other window? We have employees who will use our system but open it again from their favorites. If they do this the already opened window will run the interval and then timeout. So while they are working in the new window they opened they will not be able to finish what they are doing because the other window timed them out.
Are there solutions to do this if a new window is opened?

In any sane web application, it is safe to have multiple windows open – especially in respect to session timeouts, because "session" state is managed by the server, not the client.
First, consider why web servers manage session state. HTTP was designed as a stateless protocol, which means any given request cannot conclusively identify who issued the request. This is fine for serving static resources, but is obviously not useful if we want to develop a more interactive app; Netscape later added cookies to their browser to address this.
Cookies solve the state problem (since the browser will issue consequent requests with the cookie[s]), but they are inherently insecure: a malicious client could modify a site's cookies. If, for example, upon login we set a cookie called uid to the user's ID, it would be trivial for someone to fake a cookie with uid=1, which might be your site's administrator account. Oops.
This is why web application frameworks invented the "session" construct. Each time a request is made with no cookie, the server creates a new (random) session key and sets the client's session cookie to that key. The web server keeps track of sessions and all state associated with each session. Important here is that the key itself contains no data, is large and random enough (has relatively high entropy), and is useless outside of your server. It is thus not possible to know how to change the key to gain access to other sessions.
Think of sessions as a large array – one item for each session, and a map of variables in that item. Conceptually, it might look something like this: (remember that this data resides on the server!)
session['safa4fwsa34rff4j9'] = { uid: 1, ... }
session['ajiokinmoi3235000'] = { uid: 4312, ... }
session['9lij34fff032e40k0'] = { uid: 9098, ... }
If I was signed in as user 1, my browser would send a cookie with sid=safa4fwsa34rff4j9. The server looks up this session, and passes the saved state ({uid:1}) on to your scripts. When your scripts are done, the server saves any changes back into its data store. (Session data is often kept in-memory, but in large sites, session data can be saved in a database.)
So what does all of this have to do with timeouts? This session data cannot be kept indefinitely because you'd eventually run out of storage space (whether that means running out of RAM or filling up the database your sessions are stored in).
Instead, the server also stores an expiration date & time with each session. Each time the session is accessed (by a client sending a request with the session's key), the expiration date is reset. The expiration date can be set anywhere from a seconds from now to years from now (depending on what server you're using). You configure how long you want your server to hang on to sessions; IIS defaults to 10 minutes, PHP to ~24 minutes.
In this model, the only thing that really matters is the last time a client issued any request, thus resetting his session's expiration/timeout. It wouldn't matter if multiple windows are open, because as long as one of them have accessed a page recently, all windows will still be active. If the session expires, then all windows are automatically expired when they make their next request.
Something that might muddy this issue is if you're doing some kind of AJAX polling, but the question doesn't indicate what technologies are being used. (#OP, it would be helpful if you included tags for your server stack.)
To summarize all of this: If you're doing any kind session management/expiration on the client, you're doing it wrong. Your app is likely insecure.

Related

Express Js: req.session vs cookie vs local storage vs session storage

I am new to Express JS and frontend. I am developing an app which is using req.session for maintaining the user session and local storage for storing some other temporary info.
I have seen various articles for differences between the above but I am still unclear which is used when and how long does each persists.
According to me:
1.req.session: The server maintains this session. This gets cleared when user clears cookies.
2.cookies: Cookies are sent to server to maintain authentication
3.local storage: This persists till user deletes the cookies?
session storage: This is maintained by browser and persists for one tab.
All are different type of storage mechanisms commonly use in web application development.
But The matter is choosing the correct one.
In Short
Cookie Storage
Cookie is a browser storage mechanism, But can access from server-side through request. Developers use cookies to store data which should be accessible from server and client.
Example: Authentication Tokens, Analytical Data
Session
Session storage is a server-side storage mechanism which can be only accessed by server. So we cannot access from browser directly. Use sessions to store confidential information.
Data in session will be destroyed when the session is closed.
Local Storage
Local Storage is like Cookie BUT we cannot access from server, we can store much more data than cookies and it doesn't expire unless we clear.
Cookies - 4 KB &
Local Storage - 5 MB
Session Storage
Session Storage is similar to Local Storage. But the only difference is, Local Storage doesn't expire But Session storage will be destroyed when page session ends. Session storage keeps different session per page (tabs)
I'll go through each of your points and discuss them...
1) req.session: The server maintains this session. This gets cleared when user clears cookies.
If you're keeping this in a persistent store (disk-backed data store), you can keep this state for as long as you want. The server will lose track of the client that it corresponds to when the user clears their cookies. Depending upon how you manage your persistent user storage, you may be able to rebuild a previous session object when the user logs back in again (allowing you to use their userid to find their lasting state in your database, create a new session cookie, build a new session object from that and reconnect that browser with a new session object).
2) cookies: Cookies are sent to server to maintain authentication
That's an over simplification of the utility of cookies. Cookies allow a server to set some state in the user's browser that will be presented back to the server with each request from that specific browser. Cookies are often used for keeping track of an authenticated client and often used for keeping a key to a server-side session object. There are thousands of other things cookies can be used for too (user site preferences, tracking ids, other user state, etc...).
3) local storage: This persists till user deletes the cookies?
Browser local storage has no connection at all with cookies. It is a separate local data store in the browser that is accessible only to client-side Javascript in a web page. Deleting cookies has nothing to do with deleting local storage. They are separate items that can be separately retained or deleted. The server has no access at all to local storage. In addition, local storage is segmented so that the local storage values form one web site cannot be accessed by Javascript in pages from another site.
4) session storage: This is maintained by browser and persists for one tab.
It's not quite clear what you mean by "session storage". There are "session cookies" which are purposely designated upon creation to only persist while a given browser is running. If the browser exists and then some time later is restarted, any session cookies will be gone. Their purpose is generally for short term cookies, not meant to persist beyond what the user is currently doing.
One other possible thing you might have meant by session storage is long term, persistent storage on the server (typically in a database on disk) for various user properties or state that you want to last a long time. Imagine the user populates a shopping cart and you want them to be able to keep that shopping cart indefinitely as they move from device to device and as they add/remove things from it over a significant amount of time. For these types of things, you won't typically rely on a session object to keep track of these, but will use a database as the main source of that data. It's possible some subset of data currently being worked on might be cached in a server-side session object, but that would only be for expediency, not as the long term storage for it.
Or perhaps you meant Window.sessionStorage in the browser. That works like localStorage, but only persists for the duration of the browser being open (similar lifetime to session cookies) and unlike localStorage, each tab or window has its own sessionStorage. Like localStorage, each origin has its own sessionStorage some a page from one origin can't access the sessionStorage for a page from a different origin, even if they were both loaded into the same window/tab.
In order to help you more specifically with your application, we would have to understand each piece of state you wanted to keep track of and what it was used for. Only then could we suggest what mechanism might be best for storing it.
req.session
When a user visits the site, it creates a new session object for the user and assigns them a cookie.
Whenever the user request from the same client again, the cookie is checked, sent to the server for processing and the session information stored is updated.
The difference between Cookies, Local Storage(LS) and Session Storage(SS) is as follows.
Cookies is processed server side, while LS and SS data is never sent to server. They are stored locally.
Storage capacity of a Cookie is max 4 KB, while for LS and SS is more than 5 MB.
Cookies mostly store only the session id. While LS and SS can store more information like user information or page browsing history.
SS gets cleared when a user closes tab(session ends). While Cookies can be deleted by clearing cookies and LS can be cleared by deleting Browser cache.
I will update the answer if I remembered anything else.

Store sensitive information on the client side (Web)

I develop a website and I need to store a private key on the client side.
How to securely store this variable on the client side?
Can I use sessionStorage?
(I would like this (variable) information to be accessible only to the current user. As soon as he closes his browser, the data will have to be deleted.)
Thank you.
At a top level, yes, sessionStorage will do what you need. To quote MDN’s page on sessionStorage:
A page session lasts as long as the browser is open, and survives over page reloads and restores.
Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
Closing a tab/window ends the session and clears objects in sessionStorage.
There are several things to be careful of though. Firstly, any connection to the server would need to be done securely. This necessitates an HTTPS connection, probably with TLS 1.2 or 1.3 at this point.
Secondly, you’ll need to make sure that the page environment is clean. This means that you can’t load 3rd party JavaScript that could exfiltrate the private key. At an absolute minimum, any third party JS you load will need to be audited first and then have an integrity attribute added to make sure it doesn’t change.
Finally, you probably would want to add something to destroy the key after the user has finished using the page. This could be warning them to close the page after they’ve finished using the system, or something more automatic like retiring the key after x minutes and getting the system to negotiate a new one in time. Obviously there’s a balance here between security and usability, but the best systems can do this in a user-transparent way.

Is there a way to cache JSON on client side for limited time in order to avoid making 2 GET requests to the API if the user visits the same page twice

Imagine this scenario - A user visits their profile page on URL /user/username and the component that loads on this URL has to make 1 GET request to the API in order to obtain the information about the user with that username. So far so good, however, if the user visits another URL and then decides to come back to the profile page with URL /user/username, the component makes a new GET request for the same information that it got earlier which leads to 2 drawbacks - the information doesn't appear instantly as the component has to wait for the GET request and I'm making a second call to the API.
This is why I am wondering if it's possible to somehow cache that information so that when the user visits his profile page again, the component wouldn't have to make a second GET request. Also this cached information should be able to expire after a certain amount of time like an hour so that it is never inaccurate.
Is this achievable and worth it?
I personally would first try the http-caching solution as mentioned by "Sudhakar RS", but next I would try session storage. There is a vue-sessionstorage plugin as well. Of course your data then would be valid for the session. Should your session be longer than the hour you mention you would have to manually handle that as part of the data you save with a timestamp. There is a sizelimit of I think 5MB for all session storage data. If you need more then I would go with what "Hung Nguyen" suggested.
You can use browser Local Storage or WebSql or IndexedDB to store data on browser but be careful, they has limit size.
You should cache data on server side instead client side, by this way you will have more privilege to manage your data (caching size, flush cache, ...)

Web page authentication and sessions

I'm trying to understand how most online websites authenticate and then store your session. What I'm particularly trying to understand is when I log into a website it starts off by redirecting me to the login page and then validates my username/password, then navigates back to where I started but with my information displayed. If I were to navigate away from that webpage and then come back to it sometime later I'm still logged in. I feel like this is what a cookie could be used for but I'm looking to see if anyone could provide me with a good explanation as to how this works?
A cookie is a bit of data stored by the browser and sent to the server with every request for instance a subscription status on a website.
A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)
Session values are reset after the connection is closed. Cookies values are normally saved.
Session values are usually reset after a period of time has passed without a connection from the client with which the session is associated. Cookie values are saved until their expiry time (or the browser is closed if one isn't set). Expire immediately overrides are available for both

Single page apps: auth token management and browser refreshes

When working on an Angular app, I have a single page app that communicates with a JSON web service for data.
A "login" in my Angular app is really just exchanging a username/password for a token. That token is passed as a header on all subsequent requests so the server can authorize them. This works great until the users refreshes their browser window of course (via refresh or leaving the "page" and returning).
Obviously one option would be to make the user enter their username/password again, but that seems like a good way to not have any users.
I can think of 4 options:
Store token in a secure session cookie. (What I'm doing now. I am only using so the client can read. Not used or wanted on the server.)
Store token using local storage of some kind. (Would be insecure and
require manual expiration maintenance.)
Prevent user from refreshing browser with some "onbeforeunload"
code. (I don't like when I get the "are you sure you want to leave
this page" messages and I assume others feel the same.)
Include token as part of url. (Could make url's look big and messy. Possible physical security risk. Might make for extra work with bookmarking and expired tokens.)
Is option 1 the best option for this functionality? Is there something better to do than all of these?
I think option 1 is the best one for your use case. All major web frameworks have support for this option.
In case you need to handle this manually you need to ensure these steps:
The web service will process the initial authentication request by creating and setting a secure authentication cookie. The auth cookie should be time based(only valid for a specific time interval) and its value should be a unique value if possible;
After the initial authentication request all subsequent requests will pass the authentication cookie with the request header automatically - this is handled by the browser.
The web service needs to handle cookie based authentication on subsequent requests by validating the cookie value and returning an error if the cookie has expired.
You need to ensure a client side global authentication handler captures any authentication exceptions and displays a friendly message to the user.

Categories