Checking session expiration in the browser - javascript

I am working on an app that must use session timeouts.
The problem is that users regularly miss the session timeout and lose data. I already implemented a small session keeper in javascript that will renew the session every one minute if there has been some activity in the browser, but users are still somehow losing data (assumably they are half filling out a form, walking away from their machines and coming back after the session has expired and submitting the form.)
I would like to find some way to warn them that their session has expired. The problem is that I can't figure out exactly how to do it. I can't check the expiration of the session cookie in javascript, because it's an HttpOnly cookie, and if I do some kind of AJAX request to check the status of the session, it will automatically set a new expiration for the session.
Can anyone see a way around these obstacles?

This isn't a direct answer about checking session time-outs... but I've found garlic.js to help when I'm worried about users losing their work in forms. Basically, it's a JS library that takes care of saving form data in the user's browser's local storage until the form is submitted. So that, in case the browser closes or the session expires, the data is not lost. So this may be a good backup solution for the from data getting lost part.
UPDATE:
What I typically do to avoid form submission after session timeout is to set a javascript timer that will auto redirect the user to a session expired page (with an easy log in again button) a few seconds after the typical session timeout length. (You could reset this timer with your AJAX polling when there is activity within the page.) This combined with garlic.js, combined with "deep dive" functionality (whereby you store authenticated URLs in the session when they're accessed so that after a timeout and log back in you return the user to the last page they were on) creates a pretty seamless timeout, log-in, resume where you left off scenario.

Related

CodeIgniter protect sensitive data in HTML when user leaves browser open

I have a problem and after some research online was unable to find other people with this same issue.
I'm designing a site that has sensitive data the user's work with in the page content. It uses CodeIgniter as well as CodeIgniter's session and cookie implementations to track user activity and determine when a session has expired. when sessions expire, the user has to log in again either through a sign-in portal or through a sign-in popup.
My issue is if someones working on their computer then just gets up and walks away from the browser, the session expires, but they didn't realize the session would expire then return to their computer to finish their work. There is a regular ajax call that checks if the user has been inactive, and if the time threshold is reached their session data will be erased and the session is no longer active. There is then a popup window prompting the user to sign in again if they want to keep working.
The problem is, how do I protect any sensitive data in the HTML in the meantime? You might think if the session expires just redirect the user away from the page, but if they're in the middle of something I don't want to erase all of their work. I could try just hiding the HTML using javascript, but then someone could just open the inspector to see the HTML. is there some way I could prevent anyone from seeing the page data at all unless the sign in a popup is completed?
Thanks for any input.
I don't know of anyway to protect their work like you're asking.
I'd suggest saving the users work in a draft format, as they enter it. Then if they walk away and get logged out it doesn't matter, the work is still there when they log on next.

Is it possible to make an async call and not refresh the session in PHP?

I have an alert that pops up when the users session is about to expire and when it does expire. The issue is that if multiple tabs are open for the app, multiple alerts will get fired in succession which is very annoying.
I'd like to make a check on the backend for session information before showing an alert. That way if in one tab the session is about to expire (according to the front end), but it's not actually about to expire because you've been operating in another tab, the alert won't display and steal browser focus. Ideally I'd like this to remain as an alert so the first and proper display of the warning does take browser focus.
So is it possible to make a request like this without refreshing the session?
Trying to do this in JavaScript is silly - it will be really hard to keep the countdown timer in sync with the PHP session.
If you are implementing a hard timeout on the session then you must already be using a custom session handler - so simply implement a variant of that in your Ajax responder which does not lock or write back the session.
OTOH if you're not really implementing a hard session timeout, and you are not already using a custom session handler (which I suspect really is the case). Then just check the timestamp on the session file.

Maintaining client side page state on page refresh in angular.js applications

I am building an Single Page app using angular.js and I am facing this issue for which I am not able to find the right answer.
When we do a full page refresh in an angular app, how should we check if the user still has a valid session ?? State Provider or UI router merely routes the url to the requested page, but what if the session of the user has expired ?
One thing that comes to my mind is to use a service and store a Boolean value there once the user logs in and on every page refresh or state change, we check this Boolean and redirect the user to login page, if this value is false. But, if we do a refresh, this Boolean value is reset.
Thought of storing this key value in a cookie or html local storage, but how safe are these values getting stored here. Some one can reset the value of this Boolean to gain access to a page.
Please let me know.
To make a client-side app secure you will need to involve a server of some sort. Storing values in cookies or local storage will not do any good as these can be manipulated by a user (as can everything else on the browser).
Not sure what options you have available to you but I would recommend looking into Nodejs/Expressjs/Passportjs - this is a pretty awesome combo and very good support here on SO.
Once you make progress in this area you will then be in a position to ask a more focused question.
I think you're conflating a few concepts here.
One - is the user authentication to the server. It must be the server, otherwise the concept of a user session in a client-side-only app is useless. This is facilitated (typically) by an authentication cookie. The cookie is a security token given to the user and signed by something secret on the server. The cookie contains things like login name and expiration. The cookie is validated by the server on every request the browser makes.
Two - is the nice user experience maintained in the client-side app. What I mean by that, is that if you didn't check whether the cookie has expired, your ajax calls to the server would (and should) fail with HTTP 401 - Unauthorized. You likely would want to prevent that, and have your app preemptively redirect to a login page, or if applicable, request to refresh the security token.
So what does all of that mean?
Enforce authentication on the server
Create a loginService that checks session expiration from a cookie, or whatever else you use fo your user authentication.
Use resolve parameter of $routeProvider or $stateProvider to have the loginInfo available to controllers. Here's my answer on SO to a question you might find useful.

Resuming session with an AJAX call

My app has a session timeout after 30 minutes. If the user has a "permanent login" feature activated, then on a subsequent HTTP request the server reads the "perm session" cookie and restores the session.
However, if the user does not reload or navigate to another page after his session expired, but rather clicks on a button that retrieves data via AJAX, the session is not resumed; in the DIV where the data was supposed to be loaded into, a login window appears instead.
This leads me to an assumption that AJAX calls do not carry cookie information with them. Am I correct, or have I missed something else?
Update:
backend: symfony 1.2 (PHP framework),
frontend: Prototype
Update2: it was a bug in the application, not an issue with cookies
Sounds like you are restoring the session, but not providing a new auth cookie. You might want to try a technique that I've written about on my blog of having a client-side timer that will prompt the user right before the session times out and, when they click OK to renew it, will make a request that will serve to keep the session and authentication cookie alive. You can find more info at http://farm-fresh-code.blogspt.com. The article is titled Client-side Session Termination.
An XMLHttpRequest call should carry cookie information like normal. You may be running into a bug. Are you ensuring the call is from the same domain origin?
Perhaps your cookies are also expiring? More info might help .. :)

force to login user on each new browser session?

I want to logout user if browser is closed and force it to login again on turning the browser on.
if (!(isset($_SESSION['admin']))) {
header ('Location: login.php');
}
This doesn't work - because turning off the browser does not mean drop the sessions on server - if I understand well a lot of posts on SO and outside.
Using javascript to delete sessions just before closing the browser often doesn't work because browser will not wait to execute any code if user clicks to close the browser.
Second option is keeping server session alive by sending a js code from client (setInterval - ajax).
Problem here is scenario with multiple pages open on different tabs/windows, i.e. interference between multiple setInterval functions.
I also tried this:
session_set_cookie_params(0);
session_start();
This also doesn't work - after turning off/on the browser index.php is open without redirecting to login.php.
The reason is maybe browser option to automatically restore previously loaded pages.
So, what to do ?
#Axalix wrote:
If session relies on cookies, you just need to keep expiry date empty, then when browser / tab is closed this cookie will be removed from a browser automatically. That's a standard browsers behavior. Yes, the server will still keep it, but since browser doesn't have it, user will need to relogin
You responded:
could that be a possible security issue because cookies are javascript stuff - chengable by client?
Yes cookies can be changed by the client but Axalix' answer from the comments is still the best if you intend to use $_SESSION. If you want to end session on browser exit so that a 2nd user doesn't come later and take over the old session, then you must trust the owner of the session with the session cookie.
If you really want to break access as soon as the client leaves, then $_SESSION is not the best tool to track login state. Instead you could use WebSockets. The socket remains open as long as the webpage is open. Once the socket closes, you can invalidate any login state.
This may be more trouble than it's worth though, so think hard about whether it is really that important. As an alternative, you could use SessionStorage, which is destroyed when the browser closes but it's also available to the user (so a user could just copy and save what's in SessionStorage, then recreate it later).
Basically you need to trust the user who provided you the username and password.
There are couple options but all end up same way. you can either store something in sessionStorage to check session. when browser is closed session storage will be wiped out. or you can add a hidden input field and assign a value per session. if page is newly loaded and value exists that means session is still active, so you can redirect to logout and show login page in either way. but second option may not be usefull if your app has page reloads. I think sessionStorage would be your answer. set session on sessionStorage on login, if it is empty. then check session storage on page load. if it is empty that means user first time on there, since page reload will keep the value.
When Google Chrome is configured to re-open all previous tabs, it won't delete your session cookie. See for example this question asked 5 years ago, but stil an issue (just verified, Google didn't change that behaviour). Unfortunately you can't do much about this behaviour (as far as I know). Without deleting that cookie your session still remains open (unless it is deleted server-side during clean-up).
Best solution to handle an automatic logout is to store a 'last activity time' in your session, update it in every request and in your 'is logged in check' verify that the last activity was not more than, say, 15 minutes ago. If it is more than 15 minutes ago, you could send him to the login.php.
To improve this furthermore (and if this is really an issue for you), you can use a setInterval in javascript to send keep-alive AJAX-calls to the server every 30 seconds or so. In that way you can lower the 'last activity time' (either real activity or automated) limit from 15 minutes to 2 or 1 (leave some room for network hickups).

Categories

Resources