I <3 Steve McConnell*
Coding Horror
programming and human factors
by Jeff Atwood

April 15, 2008

Your Session Has Timed Out

How many times have you returned to your web browser to be greeted by this unpleasant little notification:

Your session has timed out. Please sign in again.

If you're anything like me, the answer is lots. What's worse is that you're usually kicked out of whatever page context you were working in. You have to manually log in again, remember what you were doing, then navigate back to where you were and resume your work.

Most programmers look at these sort of browser session timeouts as a necessary evil -- sometimes even as a security "feature". I know my bank website zealously logs me out of its web interface if I'm idle for more than five minutes. I'm not sure either one of these reasons are particularly justifiable.

As a programmer, I understand why session expiration occurs. The HTTP protocol that the web is built on is stateless. That means every individual request your browser sends to a web server is a newborn babe, cruelly born into a world that is utterly and completely oblivious to its existence. The way modern web applications get around this is by telling the browser to send a small, unique value back to the website with each request -- this is known as a HTTP cookie. It sounds a lot tastier than it looks:

Content-type: text/html
Cookie: SessionId=5451297120

While there are privacy concerns with cookies, it is a generally accepted practice today -- at least for the first-party cookie flavors. While it is possible to maintain state without cookies, it's painful and awkward.

Every web request to that server will include its own cookie and associated session id until it expires, usually many months or even years hence. The browser definitely isn't the forgetful party here.

It's up to the server to correlate the unique session identifier sent by the browser with your individual identity, context, settings, and preferences. This is usually stored in a database of some kind, keyed by your session identifier. For performance reasons, some chunk of session information also ends up in the server's memory; there's no need to reach all the way out to the database the next twenty-six times you obsessively refresh your Facebook profile page.

Still, that doesn't explain why the web server mysteriously forgets about us. If anything, the server has all the information it needs to remember you, even if you walked away from your computer for a week. So why does the server choose to arbitrarily forget about you in an hour?

  1. Performance. Consider a highly trafficked web site. If the website tried to keep sessions alive for an entire month, that could cause the session table to grow to millions of records. It's even worse if you think about it in terms of user information cached in memory; a measly few kilobytes of memory state per user doesn't sound like much, but multiplied by a few million, it absolutely is. If this data wasn't expired and dumped on some schedule, it would quickly blow up the web server.

  2. Security. The magic cookie that stores your session can potentially be stolen. If that cookie never expires, you have an infinitely long vulnerability window to session hijacking. This is serious stuff, and mitigation strategies are limited. The best option, short of encrypting the entire connection from end to end via HTTPS, is to keep a tight expiration window on the session cookie, and regenerate them frequently.

That's the why of browser session timeouts from the programmer's perspective. But that doesn't make it right. Far from it.

As a user, I can say pretty unequivocally that session expiration sucks. Is it really so unreasonable to start doing something in your web browser, walk away for an hour -- maybe even for a few hours -- then come back and expect things to just work?

As programmers, I think we can do better. It is possible. I am inundated with session timeout messages every day from a variety of sources, but I've never once seen a session expiration message from gmail, for example. Here's what I suggest:

  1. Create a background JavaScript process in the browser that sends regular heartbeats to the server. Regenerate a new cookie with timed expiration, say, every 5 or 10 minutes.

  2. If you're worried about session hijacking -- and you really should be -- use a HTTPS protected connection. This is an absolute no-brainer for financial institutions of any kind.

I wish more developers would test their web applications for session timeout issues. Despite all rumors to the contrary, your users will not be dedicating their entire lives to using your web application in a punctual and timely manner. They have phone calls to take, meetings to go to, other websites and applications to attend to.

Is it really fair to kick users all the way out of your web application, or worse, blindly reject data they've submitted -- just because they were impudent enough to wait a few hours since their last supplication to the web server gods? In most web apps, the penance is awfully severe for such a common sin.

Posted by Jeff Atwood    View blog reactions
« Revisiting "How Much Power Does My Laptop Really Use"?
Introducing Stackoverflow.com »
Comments

I think the worst case I've run into is for a university- which politely asks if you'd like to continue your session, you click OK, but then subsequently kicks you anyways! :(

Something like that in place is fine by me- if it works.. maybe even a private pin to get you back to your previous state.

Patrick on April 16, 2008 4:32 AM

Another idea: do expire the cookie after 10-15min of inactivity, but keep state persisted for a day or so, unless the user has explicitly logged out. You might get a session timeout, but at least you'd be back to where you left, after you logged in again.

f0dder on April 16, 2008 4:35 AM

I use a heartbeat via Ajax (or more properly, via XMLHttpRequest) to keep web app sessions alive. I set the interval to be just a little less than the session timeout to keep traffic to a minimum. The session stays active as long as the user keeps the browser window open but as soon as they close it, the heartbeat stops and the session timer starts running. Works quite well.

ChrisL on April 16, 2008 4:36 AM

Actually, I've been timed out of gmail, though I haven't seen the message. It just seems like new messages aren't coming in, and then when I click the inbox, it sends me back to the login page.

Maybe it's just some other bug though.

I agree though, it's very annoying.

Ben on April 16, 2008 4:36 AM

f0dder's idea is what I usually stick to. I still find it necessary to log the user out of the application due to sensitive data, but they should be able to go back to where they were.

Shannon on April 16, 2008 4:47 AM

f0dder -- that doesn't help in the (extremely) common case of filling out a web form, walking away for an hour, filling out some more of the web form, and pressing "submit". All your data entry will be lost when you get redirected to the login.

For some reason, this tends to piss users off..

Jeff Atwood on April 16, 2008 4:47 AM

I'd rather use AJAX to persist form state to the DB, instead of hacking session timeout with a heartbeat ... more work, sure, but it doesn't circumvent the benefits of timeouts, either.

Anderw Badera on April 16, 2008 4:48 AM

As, I see, f0dder also prefers.

Anderw Badera on April 16, 2008 4:49 AM

When you suggest using an HTTPS protected connection to prevent session hijacking, are referring to just the cookie, or the whole page? If the whole page then I think an Javascript Heartbeat script hitting the server via HTTPS would be a better option for performance. I would need to test because I'm not sure if you can keep a HTTP session alive with a HTTPS cookie.

Josh on April 16, 2008 4:58 AM

I've always thought that one of the features of session timeouts is exactly that: if the user leaves his PC unattended by walking away, his session should expire so any evil doers that approach the PC while the user is away cannot do much.

Of course this is somewhat spoiled by the fact that by now every browser on earth stores passwords, but a security conscious user will hopefully decline that.

Martin Probst on April 16, 2008 4:59 AM

How are timeouts a *benefit* to the end user? In what scenario is it beneficial to me to be automatically logged out of GMail after 10 minutes of inactivity?

Imagine if Microsoft Word or Excel "logged me out" if I was idle too long in a document.

Isn't "you've been idle too long, lock the workstation" the job of the operating system and *not* the job of every little application that I run to implement in their own peculiar oddball way?

Jeff Atwood on April 16, 2008 5:00 AM

I agree, session timeouts are unpleasant. But if you're somewhat critical programming web applications (for example a homebanking solution), not only session hijacking is a problem.

What about a user, who (accidentially or not) forgot to log out and leaves the application open? The next person who passes by the PC with the open session can do anything with it - that has to be prevented, too. Yes, it's the fault of the user (why hasn't he logged off?), but from a programmers perspective I have to make sure that my application can't be compromised in every way I can imagine - and that sometimes means I have to protect the user from himself. Until now I haven't seen better solutions for that kind of scenario than session timeouts.

It all depends of course on the type of application you do, as you've made your point with the comparism to "building the space shuttle"!

Bjoern on April 16, 2008 5:00 AM

How would you handle public computers then? If your session lasts forever and you leave a public computer logged in, the next user can access your data.

In that case the timeout is there to prevent other people taking over your stuff if you forget to log out, which isn't uncommon either. And people who use public computers rather than have their own are more likely to not be fully computer literate and realise that other people can access their session afterwards.

Carl on April 16, 2008 5:04 AM

The argument I've always given for being logged out of stuff like bank account sites, credit card sites and corparate windows machines is: 'What if the user walks away from their computer?'. The idea is that you are risking someone performing the most basic of session hijacking tricks (i.e. sitting down at your computer and starting to use it). This is a pretty important security hole to consider for these applications - especially considering that many will be used from insecure internet connections (internet cafes, etc). Obviously, its much less important for less valuable data, like for example Facebook. But when was the last time you even had to log in to Facebook, let alone have your session expire?

My view: If you have something that is worth protecting (money, corparate secrets, etc) then you need the draconian session expiration. Otherwise, don't just scrap the session, you shouldn't ever have to even log in at all!

Tom Bull on April 16, 2008 5:08 AM

Keeping logged in is fine as long as it's an option, i.e. I can turn it off (either by closing the window or not selecting some "keep me logged in" checkbox) - simply to enable accessing the Web app at a public place, or using a friend's computer, etc.

Even better, though, is to not use session state and cookies, and simply go with HTTP authentication instead.

Stefan Tilkov on April 16, 2008 5:13 AM

The biggest problem of an expired sessions is that all data in the forms is lost. Often you get redirected to a login page after your session has expired, so that you have no change to copy-and-past your input to a text editor (or something similar).
The web application should save the current data in the background (this also can be used to send a heartbeat to the server). So when your Internet connection is closed and you get log out (after a certain amount of time), at least your most recent data is saved.

Jonathan Rass on April 16, 2008 5:17 AM

I agree with you: Session-timeouts are really annoying and avoidable for most of the applications out there. But in very-high-security apps I think security worries outweigh the disadvantages. I don´t want my online banking account being logged in for hours because I had to leave all of a sudden. In the meantime all kinds of malware could take control over my account. In this case I think I would prefer f0dder´s way of handling the problem.

Florian Potschka on April 16, 2008 5:17 AM

@Martin Probst: That's what "Lock Workstation" is for. Leaving a computer unattended so that any yokel can walk up and do things with it (or even just *look* at what you're doing) is a major issue in itself. "Cannot do much"? What about browser history and auto-filled in password fields?

There's little point for the browser to single this situation out. The computer auto-locking after X minutes would make a lot more sense than all your browser sessions expiring after X minutes.

Session timeouts prevent remote hijacking; they're not much use for preventing local takeovers.

Jeroen Mostert on April 16, 2008 5:21 AM

@Jeff -> "Isn't "you've been idle too long, lock the workstation" the job of the operating system and *not* the job of every little application that I run to implement in their own peculiar oddball way?"

In a perfect world this would be the case. However if a user is filling out a form and walks away without locking the PC, will that user blame the OS or the site for any loss of personal information? Granted if the form is still up anyone walking by can take info out of the form, but if the session has been expired the intruder cannot cancel (submit or close) that page to pull other personal info from other pages (say personal data, shipping address, payment info).

Zach on April 16, 2008 5:25 AM

I use a hidden iframe with link to this content:

<html>
<head>
<meta http-equiv="refresh" content="240">
</head>
<body>
</body>
</html>

It works perfectly.

Ivan on April 16, 2008 5:26 AM

html
head
meta http-equiv="refresh" content="240"
/head
body
/body
/html

That was the content

Ivan on April 16, 2008 5:27 AM

It should be made difficult, and not the default, to keep you logged into a banking site.

But if you tell the site that you're sitting at your home computer, the damned site should remember it.

Just because I only visit my credit card site once or twice a month, I'm *always* having to jump through stupid hoops like getting an "activation code" to log in...as though someone else is going to log in and pay my bill for me otherwise.

Kyralessa on April 16, 2008 5:28 AM

Another solution is to avoid sessions as much as possible, ie design RESTful-ly.

Sessions work against the underlying technology, and working against any technology always creates problems.

Benedict on April 16, 2008 5:33 AM

I think session timeouts are helpful for web applications. How many times have you walked to a public computer and found that the previous user didn't sign out? As someone said, this could be a serious problem for financial web applications.

What we've done on the apps I worked on is popup a warning about session expiration (say 15 minutes before it expires). The warning dialog contains a button that the user can click to extend his session.

Bart on April 16, 2008 5:33 AM

Wouldn't another option that would be secure (requires authentication after session expiration) but saves the form data be a better solution?

Has anyone tried the following:
Using Session.IsNewSession you can test if a session has expired, then serialize the form data and location of the current page. After login, redirect the user back to the current page, already populated.

Josh on April 16, 2008 5:41 AM

A common practice to prevent sessions to be stolen, is to bind it to a certain IP address. If someone steals such a session id (such as copy-pasting an url which has the session id as a parameter), the session still will not be recognized as yours since the IP addresses differ.

It isn't totally safe, but safe enough to take the effort to implement (it's only an additional WHERE clause for the session-retrieval-sql, guys).

Leon Mergen on April 16, 2008 5:41 AM

If I'm writing a banking application, no way am I going to trust the client to handle session timeouts for me. The OS might have the screensaver/lock-workstation functionality switched off, the browser may not clear cookies when closed down, any number of things could prevent this from working.

As a user, I'd far rather have to login again after walking away for an hour than run the risk of the next person to use a public workstation opening the browser to find themselves authenticated on my bank's website.

And seriously, do that many people wander off for an hour in the middle of filling in a form? I reckon I've done that maybe twice in 15 years of using the web. Are attention spans really that short these days?

Russ on April 16, 2008 5:44 AM

I know what application have session timeouts. So I just quit them and start new one after a while. They don't tell me that the session has been timed out before I start doing something again. There could be at least the heart beat that shuts the application so I know that it logged me out.

Some applications that I use over intranet log me off too. Then they hide the relog button behind few clicks, which is irritating. At least give me the relog page without me having to search for it.

Don on April 16, 2008 5:45 AM

what is the point of a captcha when the captcha doesn't change?

Do you want to be the most easily spammable site with a "captcha"?

capi on April 16, 2008 5:47 AM

I agree with Benedict. It is possible to create great websites without relying on some in-memory session state on the server. By using a RESTful style of architecture you are playing the web the way it was meant to be. As a plus you get a much more scalable application too!

I still use a cookie to store an encrypted user token. But this can be updated with each request-response to prevent replay attacks.

Andrew Davey on April 16, 2008 5:48 AM

"Imagine if Microsoft Word or Excel "logged me out" if I was idle too long in a document."

Word doesn't log you out, but it has a terrible habit of auto-saving - which is almost as bad. I can't turn that setting off at work, and it drives me mental. I have to work with a lot of other people's documents, and in order to get them to print I often have to make changes - but the people I'm printing for like to have their documents left in peace. If I make a change and don't "log out" _fast_ enough, then it makes those changes permanent! What a topsy-turvy world we live in...

RWW on April 16, 2008 5:49 AM

Jeff,

You seem to neglect two use-cases:

1. The cybercafé
I go in, type some e-mails, surf the web, ... But somehow my time expires and the screen is locked. Countless cybercafés don't bother rebooting the machine or killing all apps before the next user logs in, hence he will have access to all my stuff.

2. Online banking and other highly sensitive websites
Do you really want this stuff to be accessaible to anyone in case you go for a coffee and forget to log your workstation. Or worse, in the cybercafé as described above.
Plus, I do believe in these rare cases it gives the user an additional sense of security. Don't forget that these services are also being used by large masses who now just starting to put their trust in something other than the agent they've known at the counter for the last 20 years.


So here is my suggestion:

- For all PCs where the "remember me" feature is activated, assume it is located in a trusted environment and enable to anti-timeout feature.

- For all other cases, assume it is a public and/or untrusted environment and expire as usual.


Cheers,
Axel

P.S.: This ties in very nicely with "auto-save", saving you the loss of hours of typing on a big e-mail when the browser suddenly crashes. And surely, they do crash.

Axel on April 16, 2008 5:53 AM

Well I agree mostly except, I bank with two UK Banks, Natwest and Halifax. Both offer a Session Timeout Feature, Natwest is an opt out function, but I like both of them.

Natwest, 5 minutes, log out, back to log in screen but with Halifax, the session is logged out but the data is still present on my screen, so anyone could come along and note down all the details, if they select anything they are warned to log back in.

I actually like this feature in places.

Sarkie.

Sarkie on April 16, 2008 6:01 AM

ATM machines annoy me for the same reason! I should be able to insert my card, punch in my PIN number - then walk away for a few hours, come back, finish the transaction, and walk away with my money.

If anyone else just happens to walk past during that time, I should expect they'll see that it's in use and not use it either.

Ok maybe that's a bit over the top - but the principle remains. As an educated user, you don't want to be logged out of web applications. Think of the uneducated users however that may use applications in a fairly public setting and walk away - exposing their email.

As a lot of people have many of their social networking accounts and other accounts linked to their web mail - all you need is access to their email and you have all the passwords for all the possible web applications that user may need.

There should be some middle ground - like data persisting over a time out (after relogging in), but to in no way protect against unauthorised physical access to the terminal isn't right.

`Josh on April 16, 2008 6:03 AM

@RWW

I'd just save all my changes on their documents and tell them to complain to the IT department. The fact that you are making changes and having to exit "fast enough" is absurd.


In general:

The credit card companies and banks pay dearly for fraud. If you walk away it's unlikely you will have to pay a thing. I'd prefer not to be logged out, but really you should have to deal with whatever they give you, because they are the ones at risk.

Ideally there would be something you could sign that says "I want to be logged in at all times and I'll be responsible for any and all charges, blah blah", but I guess there are legal reasons why that's not possible.

(I also think that stores should be required to check ID for every credit card purchase, and if they don't, the fraud is their responsibility. But if you want to sign something ahead of time that says "I don't want to show my ID, and if someone uses my credit card then I'll be responsible", then you should be able to do that too.)

jon on April 16, 2008 6:11 AM

I HATE being logged out do to inactivity if I'm sitting at my desk and go to look at something else. However, I also understand the need to keep certain applications secure (banking etc), so the auto-logout is necessary.

Perhaps one solution to this problem would be a "keep me logged in" check box, that isn't checked by default, but when it is, does the heartbeat like Jeff talks about. This would allow those of us that want to keep the session alive to do so. However, I don't think this will pass muster w/the security Nazis of some institutions. We would probably still have to throw them a bone and set a timeout, but it wouldn't be for a short time (say you've been idle for 2 hours). Now, when you get logged off this time, you've been idle for a really long time, and you *probably should be* logged off. However, it wouldn't be a "typical" logoff. Instead, it would write an encrypted cookie that contained all the pertinent information needed (if possible), then the login process would look for this cookie, and would restore you to the proper state (yes, I know this isn't possible for everything....but it is better than what we have now).

mjmcinto on April 16, 2008 6:16 AM

I think this has a lot to do with how "modern" web applications are built. Most examples I see of web apps (at least in the Java world) involve holding lots of things in memory. User beans, session beans, application beans, pinto beans, all floating around in memory...it's just nuts.

What needs to be done is use a database (and all non-trivial web apps probably have a database or two anyway) to hold all this session stuff. Maybe things could be *cached* to make things faster for more active users, but don't drop the session after X minutes of inactivity.

Truthfully, there probably isn't a need to cache the session either. Given that we're talking about transferring data over the internet there's going to be a significant delay anyway. Let the database itself maintain the cache - the penalty to reads from the database are minor compared to the network penalty.

APH on April 16, 2008 6:21 AM

What we should do is allow a read-only version of your site (that still requires a login to see). Then when you want to submit data, if you're session has expired, prompt for a login using a javascript popup, then continue the data submission. This allows for multiple levels of security on a site making it only slightly inconvenient if you've been idle for a long time.

BenC on April 16, 2008 6:23 AM

http://en.wikipedia.org/wiki/Cross-site_request_forgery

One of the main reasons sites with important user data have an interest in you being un-authenticated as soon as you're done using their service, HTTPS or not. To assume that on the open web, especially with people using IE, and especially considering most people probably don't do updates --- that you are the only one who makes requests on your machine, is silly. Mom and pop visit that spam link and suddenly make a bank transfer without every knowing better.

Brett on April 16, 2008 6:24 AM

@Jeroen:
> The computer auto-locking after X minutes would make a lot more sense
> than all your browser sessions expiring after X minutes.

Of course, but if you're the responsible man in the bank or online-shop-administration, you would let expire sessions in spite of beeing sued afterwards and be responsible for a punitive damage of some milliions.
The complainer could argue that it is "state of the art" to let sessions time out, and that you have not.
That Windows or Linux could handle this by locking the workstation is often unknown to infrequent pc-users.

If it's only facebook, don't time out.
If it's financial data, time out if the user has taken no action for about 20 or 15 minutes. Or you should have big cash reserves to donate.
Of course you should persist as much as possible and preserve state.

titrat on April 16, 2008 6:24 AM

When my users' sessions time out while posting a form, I show instructions on how to preserve their data: login in a new window, then return to this page and refresh to re-post the data.

doublefudge on April 16, 2008 6:24 AM

I work in the medical industry, and for us timeouts are a security feature. (On our app, we originally had it set to ~2 hours, and then had to reduce it due to security concerns.) We allow users to save partial data, since it could concievably be weeks to get some items needed on a form, if it's something that will have to be verified by someone in a lab or clinic. (We do pop up a message box to let the user know that their session's about to expire.) Shared computers aren't just a worry in internet cafes. Nursing pods also often have shared computers, which are regularly left unattended, as the nurses do their real work.
I've also worked on desktop apps that would log you out after 30 minutes of inactivity. It was a common enough requirement that it was supported by our tool set.

Mike Swaim on April 16, 2008 6:30 AM

What I like to do is similar to solution #1 in your post. If I know my session timeout is 20 minutes, I will add a javascript timer on my page that will be for 18 or 19 minutes. When it reaches zero, I pop up a javascript confirmation window to the user asking if they are still working on the form. If they click yes, then it causes a postback, thus renewing their timeout. If they don't click yes, or click no, their session times out (probably because they left the computer). This works particularly well for a survey website I made. Users hate it when they spend 20 minutes (or more) filling out a survey with additional comments for each question just to have the session timeout.

Mike on April 16, 2008 6:33 AM

Let's see here...

IP = stateless
TCP/IP = built on IP, stateful
HTTP = built on TCP, stateless
WebApp = build on HTTP, stateful

...what's wrong with this picture? Might it have something to do with why the web is so goddamn slow?

And what's next? Is some genius goiung to find a 'clever' way to add a stateless layer on top of web apps?

Captain Obvious on April 16, 2008 6:36 AM

Thank you *so* much for addressing this.

I can kind of understand it with my bank. After all, Bank of America has to be under a constant barrage of attacks, and it would really ruin my life for a while if one managed to succeed against my account.

But for a lot of applications its just stupid. For instance, the little online web game I play at home. Its realtime, and resource collection based, so the typical workflow is to issue a couple of commands, then wait an hour or two before doing it again (or go to work or bed and check again when next near the machine). That means pretty much *every* time I get the session expired message. Why even bother in that case? You might as well just get rid of the "session expired" page and make me relog in after every command. Its still massively stupid, but it would at least save me clicks into and out of that "session expired" page.

The worst I've seen is the World of Warcraft forums. The session timeout there is something like 10 minutes. For a flip little message, that's fine I suppose. But often it happens that I have a post I want very much to get right. (EG: A detailed explanation of a bug I'm having trouble with) I spend a lot of time editing and rephrasing it to get it just right. Then when I'm finally satisfied I click the post (or preview) button, only to get a "session expired" message. The back button simply takes me back to the posting interface with a *blank* text edit box. All my work is gone! That is *so* frustrating.

I've actually taken to composing posts in emacs and pasting them in the edit box when I'm ready. I just can't trust my content to Blizzard's user interface. But sometimes I forget and loose another 20 minutes of work. Grrrrr.

Seriously, unless you are Bank of America, don't do this.

T.E.D. on April 16, 2008 6:37 AM

Amen!

Not long ago, I was filling out a contact form on my bank's website. I had a lengthly message that I was sending them, with a bunch of information about some particular transactions against my account. It took me about 20 minutes to compile the information and write the message. When I hit submit, I got a message that my session had expired. My message was not sent and I had no way to recover it.

I had to compile the information again, and type the message again (this time into Notepad) before logging back into the site and going to the contact form to paste it all in.

I complained but they basically didn't believe me. I was supposed to have gotten a popup asking if I needed more time. A popup, seriously? With popup blockers built into every browser now, they rely on that?

-Jeff

Jeff Handley on April 16, 2008 7:06 AM

Jeff's post next year if session timeouts are actually removed:
"
Why do I always have to log out from web applications? If I login to check my mail at a public computer in the library, then leave, everybody after me can access my mail! Web sites should be smart enough to log me out automatically if I haven't used it in a while. I shouldn't have to remember to go through a logout process every time."
"

a on April 16, 2008 7:13 AM

I think you touched the main problem at the beginning of the text: restoring context.

Expiring cookies aren't bad, throwing the user back to the doorstep when they have expired is. Unfortunately very few sites get this right at simply sneak the password question in before getting you to exactly the page you wanted to see.

Of course the security levels are quite different here. I quite like what they do at amazon: They'll know how you are but require you to enter your password before placing an order or digging through your order history. Banks, however, never get anything right in this respect.

ssp on April 16, 2008 7:14 AM

HTTPS is always a (compulsory) complement, not an alternative. However, I see your point. In online banking, the solution should be obvious: Actually, I don't see any reason for the user to stay logged in at all. Online banking is not a continuous activity, it's more like a set of distinct (trans-)actions and each of them should (MUST) require individual authentication (notice that this *is* actually the case with PIN/TAN authentication; so why bother with the classical login at all?). If you prefer comfort over security, have your browser store the login data (and preferably have the site use HTTP authentication mechanisms as opposed to HTML dialogs). The current approaches to online banking that I know are, in my humble opinion, fundamentally wrong (I could exclude SmartCard-based approaches but I'm not sure I'm going to). But as long as they continue to use the classical login mechanism, session timeout seems crucial to me.

For other, less transaction-driven applications I don't see why the heartbeat approach shouldn't be taken. XSS *could* be a valid concern. Let's not forget that paranoia is a foundation stone of the security business.

Konrad on April 16, 2008 7:14 AM

Session expiration for the purposes of preventing unattended computer attacks sounds good at first, but what about non-web software such as banking tools, business information, address books, etc? That's all just as vulnerable on an unlocked computer as web applications are.

The responsibility for securing the local access point belongs to the user, not to the application, not to the OS. Certainly the app and the OS should do their part to limit, or eliminate, weak security points, but the ultimate responsibility still lies with the user. The app is not responsible for securing an unattended, unlocked workstation any more than Ford is responsible for securing an unattended car with the keys in the ignition.

J. Irvine on April 16, 2008 7:24 AM

Websites that DON'T expire sessions piss me off, but then I guess that is because I work in Application Security and realize that Session Hijacking via sniffing an unencrypted channel is the lowest risk attack I need to worry about associated with the session.

If your site has cross site scripting on it, and about 80% of websites do, including the big sites out there, a simple document.cookie has now given me your session (or if you set the httponly flag in the cookie I have to jump through a hoop making a XMLHttpRequest and parse the response to get the cookie), and if that session never expires I can be leisurely about using my newly stolen session.

Or, I could put a snazzy little iframe on my site to amazon, or gmail or wherever, and since you are still logged in I can make all sorts of forged requests to those websites as you (See Brett's post about CSRF).

And now that the retarded HTML 5 working group wants XMLHttpRequest to be cross domain and pass cookies (thankfully MS told them go go shove off about that, and now so has Mozilla) your unexpired session would be all the more useful.

Binding to an IP is of limited use considering the tremendous use of load balanced proxies in the world. AOL users, for example, are notorious for connecting over several load balanced proxies, so their IP bound sessions would be invalidated all the time. The best you can do is bind to the first three octets of the IP if you don't want usability to completely suck, much worse than with a session occasionally expiring.

Session expiration is a necessary evil of the technology; sessions are a hack to begin with and as a result have plenty of security concerns. Yeah, it sucks for users, as does even having to use a username and password (inherently weak authentication with crap for usability- how many users really can be bothered to put an upper, lower, number and special character in their password) to sign on in the first place. However ignoring security concerns in favor of usability is a Win98 approach to things, and as I recall that ended pretty poorly.

Joshbw on April 16, 2008 7:32 AM

"Is it really so unreasonable to start doing something in your web browser, walk away for an hour -- maybe even for a few hours -- then come back and expect things to just work?"

Yes, absolutely. This would be paramount to leaving your card in an ATM machine. Are you honestly suggesting that everyone who has access to your PC be privy to every piece of personal access you might have forgotten to close ?

Users aren't perfect. If you don't force them, they'll leave their online banking site open and logged into for days ("It's so inconvenient having to log back in every morning"), just like they will leave car keys in the car (that's why cars make beeping sounds nowadays) or their cards in ATMs (that's why ATMs spit out your card first). Security doors close on their own. Front doors usually lock on their own if you pull out the key and close it. SSH sessions time out after a period of inactivity. Safe doors relock themselves after 30 seconds. Windows by default goes to the login screen after the screen saver turns on.Even cellphones lock themselves if you turn them off. Why would things such as online banking be expected to behave differently ?

Of course, this applies much less to websites that are less volatile than online banking, such as forums.

J. Stoever on April 16, 2008 7:37 AM

I really agree with the point you made here, it shouldn't be the user's job to worry about sessions.

It really cripples the user's experience.

h3 on April 16, 2008 7:40 AM

I think sessions should time out. People should get on the computer, do their business, then get off and go do something like play with their kids, interact with humans, plant flowers, etc.

Go rent "Farenheit 451".

Steve on April 16, 2008 7:45 AM

My solution was to stop putting so much stuff into Session and use the ASP.NET profile, which in turn uses a database store. Sessions still expire but most items can be retrieved quickly from database and the user can pick up where they left off.

Matthew Martin on April 16, 2008 7:46 AM

You can always "ajax-ify" your login so that upon submitting a form it allows you to log in BEFORE submitting the form and therefore the hard work you put into the form isn't lost...

Kearns on April 16, 2008 7:46 AM

An ex-boss of mine told me about a credit union website, that when the page lost focus, would expire your session. I told him it was the stupidest thing I'd ever heard of.

dp on April 16, 2008 8:06 AM

If this is possible, I would suggest something that keeps the state of the page you are on but at the same time it has a pop-in? (pop-up but same exact window/tab) that requests you to login to continue so all of your data is still available when it disappears and logs you in, in the background.


There is one session timeout I absolutely loathe, netlibrary.com.
If you even access their site after a while it will have a popup requesting you to continue your session or it kills your session (this might only be from a network with a subscription, like a university or company)

DanaL on April 16, 2008 8:10 AM

One approach is of course not to persist anything in the session state and put all the state in hidden fields. That has the downside, though, that you cannot trust the client - anyone can modify any hidden fields before submitting back to the server. It also increases the size of both the response and the next request.

Mike Dimmick on April 16, 2008 8:14 AM

I'm surprised nobody's mentioned the awesome Firefox extension "Reload every...". It's dead simple. Right-click on a page and pick from anywhere between 10 seconds and 15 minutes for the page to automatically refresh. It's saved me from many a session timeout.

Cheers.

Ben Lacy on April 16, 2008 8:22 AM

The webApp my group writes is for reporting on personal information. Stuff like income, Social security number, Address, Name, etc... And the contract specifies that we build in a time out for each session. And we are uber secure.

The applications run on a VPN, and cannot be accessed outside of the VPN. The user must exist and be able to login to the VPN to access anything. The user must login to our application to access anything. There is controlled access to the computers in people's offices with a policy on the PC that if the PC is idle for 5 minutes it locks as well.

Part of the requirements was that after a set timeout, we not only expire the session, but automatically, change the page to a default login screen without any prompting to the user. So, you could technically be reading a report, not interacting with the computer, and get booted while you are sitting in front of the PC... crazy. And it was a pain to make all that work together.

But, our customers wanted it and they have never complained. I guess with all the identity theft going on, it's a necessary evil.

Wayne on April 16, 2008 8:30 AM

Session timeouts were conceived of as a means of minimizing resource utilization on the web server. They were later latched on to as a cheap means of "security". Be wary, though, since programmers who rely on session timeouts to provide security may have other low morals and offensive habits as well.

Security costs time and effort on the part of both the user and the programmer. Use HTTPS. Consider using HTTPS with mutual authentication. If you fear a session may have been hijacked during a period of inactivity then reauthenticate the user before allowing an action to take place. Consider authenticating on every action, if the need for security is sufficiently great.

Don't just throw the user's work away.

The easy solution, session timeout, is probably the wrong solution for most problems other than the one it was invented to deal with: server resource starvation.

Rich on April 16, 2008 8:30 AM

Bret (Brett on April 16, 2008 06:24 AM ) RE: CSRF.

Thank you, thank you, thank you. CSRF is the number one reason why people should be logged out of sites, either via inactivity or after they've finished their activities on the site.

CSRF is a fundamental flaw in the way webapps work, and I really don't see all that many sites protecting themselves from it (and I work in the security industry)

There's not all that much being said about it, compared to say XSS or SQLi, and I'm certain that there's more attacks out there using this vector than we know about, but it's thankfully getting more noise.

I know that security sometimes gets in the way of usability, but in some circumstances you've just got to suck it up.

MikeA on April 16, 2008 8:34 AM

The one thing about the GMail example is that Google has more disk space than God, of course. One example that does pop to mind is Songza, which in several months of use I believe I've had to log in to once.

Pianohacker on April 16, 2008 8:36 AM

I tried ordering tickets on my iphone from the devilish business that is ticketmaster. While I'm pretty fast at typing on the phone I still found the windows of timeout it gave me incredibly annoying. At the top of the page it'd say something along the lines of "you have 2:00 to complete this page or your tickets will be released." I can't imagine how a slow typer on dial-up buys tickets online. I suspect their time windows are as much for pressuring you into buying as they are to protect their business from scammers. There's no reason I need to make a 2 minute decision on tickets 2 months after tickets went on sale and 2 months before the event.

Caleb on April 16, 2008 8:48 AM

We actually just have our session timeout set to 1 day. But we don't have anything all THAT sensitive (nothing financial) that somebody else stealing your session is that big of a deal.

Mostly it's just to keep track of who does what. I think what happens is security stuff is developed for more sensitive applications (like banks) and then people think it needs to be used for everything.

All we have behind the login is additional content. If somebody steals that extra content, we aren't really all that upset (plenty of people would rather get it legitimately).

However, when it comes to actual sensitive information a short timeout makes sense. Yes, it might be convenient to be able to walk away from your account, come back and make changes, but seriously, that's a Major Risk in many circumstances.

Not everyone logs into those sites from a computer they know nobody else touches. Anybody from other family, neighbors to complete strangers might use the same terminal you do in many cases, and the people (IE Developers) who make the websites can't know for certain that you aren't on such a terminal.

I would liken it to starting a transaction at a bank terminal or ATM, and then walking away. Do you really think that somebody else won't come along and make a withdrawal while your account is wide open?

So. I have to go 50/50 with you. On some applications the timeout is unnecessary and should go away (but you can just disable it, rather than having some fancy heartbeat). But on sensitive applications, it's a no brainier. You NEED a timeout.

I agree that most people are able to make sure nobody else uses their terminal, but as a fellow developer, I am sure you know, it's the edge cases that cause problems. And when you are talking finances, it can be a million dollar problem! Not something you want to mess with for the sake of convenience.

Jeff Davis on April 16, 2008 8:56 AM

@Jeroen Mostert: "That's what "Lock Workstation" is for."
Yes, that's right. Forget to lock your workstation, and people *should* be able to steal all your money.

"Leaving a computer unattended so that any yokel can walk up and do things with it (or even just *look* at what you're doing) is a major issue in itself. "Cannot do much"? What about browser history and auto-filled in password fields?"
What about them? I never use auto-password on anything I wouldn't allow any user to be able to access. If your bank even allows you to auto-fill the password, you have WAY bigger problems. I don't know the exact ins and outs of auto-fill, but you're at least giving anyone who sits down at your PC the chance to RUIN YOUR LIFE.
And I'm struggling to find a really destructive use for browser history. The most they could do is blackmail you about your browsing habits, and let's face it, The Internet is for Porn.

"There's little point for the browser to single this situation out. The computer auto-locking after X minutes would make a lot more sense than all your browser sessions expiring after X minutes."
Unless you share a terminal with someone. Or someone knows your locking password (entirely possible).

NB. This all only applies to software such as Banking and Online Transaction software. Anything non-financial, not so much of an issue.

Tom on April 16, 2008 8:58 AM

Pretty easy to force any website to refresh at an interval with greasemonkey...

window.setInterval("window.location.reload();", 300000);

Joe Beam on April 16, 2008 9:00 AM

The "lock" scenario is the best scenario I've seen. If a user's session has timed out (or they logged out in another tab) and they submit a form, we "intercept" the request on the server, redirect back to the original page/form, populate the fields and place a "popup" div asking the user to login. It gets tricky when you have some significant state (multi-page forms) to keep track of, but over all it works quite well.

Brad on April 16, 2008 9:09 AM

There are security reasons for timeouts. A non-expiring session cookie is still good even if I go to another webpage or quit my browser, then come back to the original webpage. Imagine someone on a public computer reading their email, leaving while forgetting to log off, then someone else comes and takes over. Like ATMs, you really need a timeout.

Why don't you get session expire messages in GMail? It's Magic! No, it's just the fact that you are signed in and identified in Gmail. When your session cookie expires, GMail saves the state of your application. Clicking on a new link will simply restore your browser and give you a new session cookie. Plus, because GMail is AJAX, it knows when you are typing and keeps the session cookie refreshed. The only way you'll time out is if you start composing an email, then leave your computer for an hour. And even then, GMail will save your draft before it expires.

So GMail's tricks are:
* You are always signed in
* Using AJAX to refresh the session cookie when you are typing
* Saving your state when the session cookie does expire

That won't work for places that let you do things without first signing in or that don't heavily use AJAX.

David W. on April 16, 2008 9:17 AM

@Jeff:

Not so. If you expire the cookie, you can still store the session id inside a hidden form field.

Now, let's say the user comes back and completes this form. Just allowing the entry is a security risk. What if, in the time you walked away, someone else sat down at your computer? No, you must re-enter your password after your session expired. BUT YOU ARE ABSOLUTELY RIGHT - YOU SHOULDN'T LOSE YOUR DATA!

So how about this:
1) Store the user's session data on the server for a long period (e.g. a day).
2) The session KEY should expire, but still be kept on the system.
3) However, a new one is generated every time you log in.

Thus, if you came back to the computer after an hour and submitted your form, the system would see that you used the old session key. It would ask you to log in and GENERATE A NEW SESSION KEY FOR YOU. However, after you have successfully logged in, IT WOULD PROCESS THE FORM YOU JUST SUBMITTED, essentially letting you pick up where you left off!

Enjoy,
Greg :)

Greg Magarshak on April 16, 2008 9:18 AM

In fact, GOING FURTHER ...

If a site wanted to be really friendly, it should allow you to LOG OUT but still save your form data, to fill out later. Let's say you have to go to a meeting and you don't want to wait the mysterious "X" number of minutes until your session expires, to make SURE you are safe. And you are in a library. And you can't just lock your computer.

So just LOG OUT and when you LOG BACK IN the site can restore things exactly as you had them!

THAT would be cool. Maybe it should be called "LOG OUT AND SAVE WHAT I WAS DOING".

Greg Magarshak on April 16, 2008 9:20 AM

Right before the session is abandoned I check to see if the user logged out, if so I persist session state to a table keyed on the user's login. Next time they login they we check the db for any persisted session data in the db. If there is they are asked if they want to resume their session. If they say yes, it is rebuilt from the db, if not it is destroyed in the db. The sessions expire every X minutes (no sliding expiration) unless the user responds to a "keep me signed in" popup that is displayed Y seconds before the session is abandoned. If the user does not respond to the popup in Z seconds, their form data is submitted (via ajax) and it is saved in session along with the page they were on when the session was expired.

BrianE on April 16, 2008 9:39 AM

I like to be able to spend 5 hours typing a 3 line comment without my session expiring, or at least without adverse consequences if it does.

David on April 16, 2008 9:43 AM

Leaving your computer without locking it is akin to walking away from your unlocked car while the keys are in it and it's still running.

Session timeouts are similar to your keys falling out of your keyswitch the radio settings and power seats reseting because you sat at a stop light too long. You need to restart the car, reconfigure the radio and move the seat back to where you had it before you can continue on your drive.

The solution here is behavior modification in terms of educating users on the nasty things that might happen if they leave a valuable asset open for all to use. Lock it when you leave it sit there or someone may just come along and steal those 8-tracks in the back seat.

Neil on April 16, 2008 9:43 AM

The issue is more about balancing the timeout value with the sensitivity of the web app. Banking and highly sensitive apps should log you out quickly, but web sites of a less serious nature should change the default timeout value to something higher, like a day instead of 30 mins.

Users expect that by closing their browser, they are done with the session and it's hard to explain to them that somebody can sit down after them and pull up their session from the browser history.

Forms on the other hand should always submit without requiring a session. I usually add a hidden formfield with a MD5 hash of the user ID plus a secret salt value so I can accept forms without having to rely on a session cookie.

Sal on April 16, 2008 9:58 AM

@T.E.D.

> I've actually taken to composing posts in emacs and pasting them in the edit box when I'm ready. I just can't trust my content to Blizzard's user interface. But sometimes I forget and loose another 20 minutes of work. Grrrrr.

A good habit to get into before submitting a web form with a lot of content in a text field -- a long forum post is a prime example -- is to do a Ctrl+A, Ctrl+C on the content field. (Ctrl+A does a Select All; Ctrl+C does a Clipboard Copy. The specific keystrokes may vary if you're on a platform other than Windows.) Then, if the session has timed out or something else goes wrong, at least you have a copy of the content you entered sitting on your clipboard, which you can save off somewhere locally and/or re-enter on the web form.

http://blog.jonschneider.com/2006/02/tip-ctrla-ctrlc-before-submitting-text.html

Obviously, this tip is only really applicable for "power users", and it doesn't help on a web form with many individual fields (as opposed to one primary large field), but I've still had it save me from losing content on more than occasion.

Jon Schneider on April 16, 2008 10:15 AM

I agree with you, session expiration sucks big time.
But there's a case you forgot, public computers. A cyber cafe or any other public access computer, people normally don't really understand what a session really is, they walk away and they think they magicaly left gmail... but then another guy comes and now he's in control of your account. People DON'T close sessions, they don't see why and there's no way for the app to warn them when they leave.
It's not perfect, of course, someone could use the same terminal before the session expired, but well, there's no other way I can think of.

By the way Jeff, this comment form keeps showing me the same word (orange) in the Captcha... is it because it recognizes a cookie or something like that?

Petruza on April 16, 2008 10:26 AM

And the answer is: Don't use sessions. When user logs in, store a security token on the server and pass it down to the client (encrypt it, etc). When client posts a new request, pass the token as part of the request (hidden variable on a page). If valid, post the data, if invalid, have use authenticate again and then post the data.

Add logout feature that automatically invalidates the token.

The only thing that should expire is the token.

If not using HTTPS, I can see possibilty the token being "hijacked" by another entity, but maybe check IP Address or location of token when it was validated.

If security is really a concern, then use HTTPS and then no one can see the token.

Jon Raynor on April 16, 2008 10:37 AM

My captcha is "orange" too! Is that by design? Or is it a "feature"?

In response to your article:
I think we're treading dangerous waters when we seek to enable the insecure habits of lazy users. Users should be encouraged to maintain the security of their information. I agree with the plethora of posts that suggest a hybrid solution: extend state, trash session.

Also, we should look to sites that get the user experience right, instead of focussing merely on our budget banking websites. For example, consider the way Amazon.com manages state. Your session is kept alive, but your ability to perform financial or identity actions will expire after a certain time. I don't know exactly how this is implemented, but I love the fact that I can leave Amazon up for hours, and rest assured that nobody can come along and buy stuff using my account without re-logging in.

D on April 16, 2008 10:42 AM

Greg Magarshak is absolutely right. Sounds like a topic for About Face 4.

Patrick McElhaney on April 16, 2008 10:44 AM

session timeouts are very, very necessary for the fact that users still routinely check their bank accounts from public terminals. until every person on earth becomes intelligent, session timeouts ain't going anywhere.

jonuts on April 16, 2008 10:52 AM

Why not give the user the option? Make him/her select whether or not they're accessing from a public or private computer? Sessions should persist on private computers, but on public machines, the user should understand that, for his/her own good, the session will terminate after time.

Brian Warshaw on April 16, 2008 10:55 AM

I did not read *all* of the comments, but it did occur to me that "locking a workstation" is a pretty nice way to deal with "session timeout" - your applications, data, everything is persisted but completely inaccessbile until you authenticate.

You could do this on a web page to some degree, with an AJAX tool that communicates with the server and simulates session. Whenever user activity is absent for the amount of time, the AJAX tool could throw up a modal login dialog required to unlock the rest of the page.

I see some issues with this... since the server side session would be maintained by the AJAX communication, so more than just form field entries would be preserved, particularly if the AJAX tool is somehow circumvented.

Jason Beck on April 16, 2008 10:59 AM

Fuck sessions. Use HTTP authentication.

Nicolas on April 16, 2008 11:01 AM

I can't believe people are still bringing the "We need to educate our users" line. Look, it's not gonna happen. Users don't learn because you feel like they should know something. We have had 50 years of IT science, and users still haven't learned. Individual users learn, but users as a whole don't, not like this, not because you want them to.

The only way to get users to learn to lock their PC is if Windows would shut down instead of starting a screen saver, and even then they probably would just get a tool that "fixes" it instead of remembering to lock their PCs.

J. Stoever on April 16, 2008 11:05 AM

The age old rebuttal, "What if the user walks away from his PC?" is so tired and so nonsensical. It would only make sense the day every malicious person waits the allotted 20 or 30 minutes before sitting at the PC of the person who walked away.

The issue can only be solved by end user discipline. No 20 or 30 minute timeout or 15 minute workstation lock is going to prevent someone from sitting at the chair as soon as the legitimate user is down the hall, or out the door, or out of sight.

HardCode on April 16, 2008 11:08 AM

"Create a background JavaScript process in the browser that sends regular heartbeats to the server"

Defeats the benefits of a timeout... more work for the server. Actually, even worse than disabling the time-out, as bandwidth is being used as well as memory for caching the session info.


"How are timeouts a *benefit* to the end user?"

Prevents your son buying crap on ebay using your pre-logged on Paypal account. Even vigilant users may forget to press 'Sign Out' at some point in their lives.... I know I have.


"Imagine if Microsoft Word or Excel "logged me out" if I was idle too long in a document."

Why would it? Microsoft are not responsable for such measures here. In a web app, the developers are charged with protecting the data that drives their site's back end or user data... therefore they must put such mechanisms in place. Word and Excel really arn't responsable for ensuring that your data is safe... that comes down to the IT administrator on your corporate network. With this in mind, I think it's safe to say that the source of DATA are ultimately responsable for its security, not a third party developer of a generic piece of software that has many uses in many areas.


It was suggested that it should be left up to the OS to log off the user if idle for a set length of time. This does nothing for security or performance as a website developer can not control every PC that visits, so the only alternative is a server side time out. All in all, security comes down to the end user... after all it is those people who share their passwords or enable the password save in their browser. That being said, time-outs are established primarily as a means of ensuring that the web server stays a web server and not a speed bump, as well as giving the developer/host a way out when legal actions suppose that their system is at fault when some user left their password taped to their machine.

Kevin Creechan on April 16, 2008 11:13 AM

In my case, the session timeout was a 'feature' -- or rather, something that WAS necessary.

It's a ticket purchasing system for a smaller endeavor: wherein, once you have said that you want to purchase 5 tickets -- those 5 tickets are temporarily held/reserved to prevent oversell of an event.

If you wander away and leave a half-filled out form: your session expires and your 'faux reservation' goes back out into the pool of available tickets.

N on April 16, 2008 11:19 AM

What I do not understand is why doesn't the server store more cookies in the client's web browser, instead of just the SESSION_ID? I know that cookies have a limit, but how much data do you really need to store in a user's session?

Cristian on April 16, 2008 11:50 AM

Session timeout is only necessary because we can't authenticate the current user behind the keyboard. There is no way we can do that reliably, at least in the foreseeable future.

We can only ease the suffering - hardware authentication comes to mind. And even there you might want to protect users against accidentally leaving their key.

Robert 'Groby' Blum on April 16, 2008 12:41 PM

Go to any local midrange restaurant. Order a beverage, and look at the menu. See if the waitress will wait an hour for you to complete your order.

Local applications (like Excel) run exclusively on *your* hardware, burning *your* resources.Remote applications do not. Security implications aside, It's economics, pure and simple.

Value-added webapps will offer an option to save form data, or do so automatically, but this costs slightly more in development.

Sometimes, on the infrequent occasion when I have a form that times out, I can sometimes use the browser's 'back' button to get back at all the nice prefilled form data. I open a new session and form in a new tab, and, if the fields are arranged nicely and logically, I can use keyboard shortcuts to swap between old form and new form, cutting and pasting away. PITA, but better than nothing (esp. on longer forms).

"your users will not be dedicating their entire lives to using your web application in a punctual and timely manner"

No, but if I see a long and complex form, I will try and arrange to use it in a punctual and timely manner. You must be hell on waitresses and other service people, Jeff. That comment makes me wonder if you accept cell phone calls when at a restaurant or bank or the checkout lane of the market.

Tarkin on April 16, 2008 12:47 PM

How about the birthday paradox?

Hacker could apply that to sessions identifiers as well.

I think you need a little more stuff than that if you want banks to care for session timeouts.

chakrit on April 16, 2008 12:52 PM

@Russ
"And seriously, do that many people wander off for an hour in the middle of filling in a form? I reckon I've done that maybe twice in 15 years of using the web. Are attention spans really that short these days?"

Aaaaaaaaaaand this is why so many web applications suck. "This is the way I do it" and "no one would ever do it that way" are practically mantras of so many programmers, even in the middle of Jeff's blog surrounded by entries on the necessity of usability testing with real people and genuine arguments.

To everyone: Stop positing bank websites and extrapolating behavior of everything else from them! Banks and other sites should take every measure to protect you financially, but shouldn't inconvenience you out of laziness! And why is everyone ignoring Jeff's suggestion that sessions should timeout without dropping state on the floor?

Myspace is one of very few sites that are good in this regard. If you get timed out or need to log in, it'll take you right back to the page you were accessing after. (It won't send the message/comment if you were writing one, but at least it won't clear it when you page back.)

Foxyshadis on April 16, 2008 12:54 PM

Jeff, I can see you are working on stackoverflow based on the topic. Are you going to avoid using username/password combos and just use passwords as you've alluded to in the past?

harpooner on April 16, 2008 1:08 PM

@Tarkin
"Go to any local midrange restaurant. Order a beverage, and look at the menu. See if the waitress will wait an hour for you to complete your order."

Uh, yes, that's exactly what restaurants do. You get your drinks, when you're ready for more drinks or finally ready to start eating you can signal or wait for the next time she shows up to order. I've had 4-hour lunches that went just like this, even in cheap places. That analogy is unbelievably stupid and irrelevant, but the fact that it's so wrong is just hilarious. (Mapping food service onto the internet, are you insane? Do we tip our web servers and get half price goods on sundays?)

You just had better have a fat tip ready for staying around so long.

Foxyshadis on April 16, 2008 1:09 PM

Personally, I like timeouts. Get off my server if you're not using it, you slob.

John A. Davis on April 16, 2008 1:13 PM

As I see it, this post and most of the discussion misses the point.

Sessions are used legitimately for user authentication on the web. Some sort of timeout for authentication also makes sense for security reasons -- however, many community internet applications provide a way that people can be logged in permanently... Services like digg.com and del.icio.us wouldn't be so much fun if you had to log in all the time.

The most sophisticated web sites have a split model for authentication. Amazon has permanent authentication for low security sections (seeing personalized results) but requires you to authenticate (and create a new session) if you do anything that's sensitive.

Most often, web programmers use sessions out of ignorance and laziness. One culprit is the stream of Win32 and Unix programmers who were tasked with moving existing applications to the web.

Most of the world's research libraries, for instance, use a software package called Voyager for their online catalogs. Voyager was originally a terminal application, which created a new process each time a user logged in. They kept this model when it changed to a web application: each user got a session id and a process id -- the web process reconnected to a long-running process each time a page was rendered.

Voyager has all sorts of problems, but the worst is that users get their sessions expired when they walk away from the browser in ten minutes. Patrons hated it, but Librarians thought it would be too expensive and complicated to build a catalog that "works more like Google". Funny, I built a search application for a bibliographic database almost as big as theirs in a weekend, and it was about as fast on a four-year old PC with Linux, mysql and Perl as Voyager was on a eight-way Sun server with an expensive disk pack...

It looks like many libraries are going to outsource their catalogs to Google or OCLC since they can't manage to deal with software developers without getting rooked.

Another suspect is languages that provide an easy to use Session facility. Cold Fusion and ASP are particular offenders; somehow PHP users never got that big into session variables. Session variables are fine for authentication for personalization, but they've got (almost) no place in CRUD apps -- at least if you want them to work reliably. Programmers shouldn't use session variables until they've had a few years developing apps without them.

The problem is that web apps store state in multiple places: some state is in the web browser and some state is on the server. If you've got some state on the server and some state on the client, the app gets wrecked when people use the back button. There are a few patterns were session variables can prevent problems rather than causing them, but they don't seem to be widely known.

Keeping short-term application state in form variables and passing it back and forth like a football is the most effective, simple and reliable answer to the problems of multipart forms.

Finally, many companies have been rooked by vendors that make CMS products and application frameworks that are entirely dependent on sessions. This is good for keeping your site from being indexed by Google... And that's about it.

Paul Houle on April 16, 2008 1:41 PM

Totally agree. One very simple thing I sometimes used to do was to use SSL together with basic auth and use the user name as the key to the data. The login "screen" looks nasty but at least, the credentials travel (encoded thanks to SSL) with each request. It doesn't prevent you from caching the user data but in case that cache entry expires, it is super-easy to recreate. Session never expires this way.
If you don't authenticate your users, one question to ask is is there anything to protect? Should you use session at all? Can you use a longer-lived cookie and use that as your user data key?

Bertrand Le Roy on April 16, 2008 2:33 PM

I don't think the "user leaves/shares the workstation" scenario is something one could prevent with expiring sessions.

If the user leaves the workstation with the browser left open, he made a bad mistake, which can get him into trouble, even if there is a reasonable short session timeout. It doesnt matter that much if the malicious guy needs hurry a little (at 5 minutes) or has any time he wants: He can screw the user. So no argument for a short timeout here.

If the user closes his browser, the client's side of the session is terminated, if "session cookies" (those which have no "expire") were used, and no harm can be done anymore by stealing sessions. No argument for a short session timeout here either.

And, besides this, i think the real problem here is, that there are forms which are that huge and painfull to fill that the user takes more than 5 Minutes.
What are they for, doing the tax declaration?

keppla on April 16, 2008 2:48 PM

Of course, it depends what the session time outs are designed to protect against. Absoultely NONE of your recommendations deal with one situation - somebody ELSE wandering up to the computer when you've popped off for a cup of coffee and transferring your entire net worth to nigeria.

The original AJAX application, Outlook Web Access, has quite a neat solution. If your session times out, when you try to do something, the login screen reappears, either in the window you were accessing in, or in a pop-up if appearing in that would cause loss of information.

Result is sessions time-out, your protected against someone sitting down at your desk if you've wandered away for five minutes, but nothing is lost if you do come back to your half-written email after an hour. (And, yes, that's exactly how it benefits you, the user, to be logged out after ten minutes of inactivity - somebody else in the cybercafe doesn't start reading all your email after the mass evacuation due to the fire alarm!)

S on April 16, 2008 2:59 PM

Jeff, big fan, but you've really lost the plot. This is done for security purposes. Non-one wants someone else reading their email or bank statement when they've left their PC unattended.

Marcus on April 16, 2008 3:02 PM

Wrong answer Keppla.

In the real world, the phone rings. In the real world, people need to juggle multiple tasks. Filling out a form might require half an hour of research to dig up something they don't have on their fingertips.

One of the worst places where people use the server language's session mechanism is for web shopping carts. Many mom and pop online stores do this, and they throw away more than half of their potential sales because session timeouts cause people's shopping carts to get dumped.

Because these systems typically don't have good logging, these businesses aren't even aware that they're burning $$. Amazon.com keeps your shopping cart for weeks... Not for high principles, but for customer satisfaction and profit.

You might not like it, but many people keep their computers running all the time. If they have a Microsoft Office document open, they can come back to it a week after they started working on it. People expect the same thing from web applications -- if you're going to give them sanctimonious bulls**t about how they can't do it, you're an enemy of usability.

We looked into this issue for the case of a large electronic publishing site. We found people were complaining about timeouts on a form even if the timeouts were 24 hours (they expected to be able to walk away from the computer and come back the next day, even over the weekend) Funny enough, we still got complaints about a one week timeout!

Paul Houle on April 16, 2008 3:04 PM

Marcus,

that's bull. If you're worried about somebody messing with your computer when you're not there LOCK YOUR DESKTOP.

Outlook and Firefox don't "time out". Microsoft Word doesn't "time out". Photoshop doesn't "time out". Amazon doesn't "time out". Google doesn't "Time out"

Web applications "time out" because people build applications based on bad practices and bad architectures. Web applications "time out" because lazy and ignorant developers put their own convenience and bad ideas ahead of the needs and concern of your computers. They should stop drinking the Kool Aid from vendors and learn the practices that work.

Paul Houle on April 16, 2008 3:09 PM

"1. Performance. Consider a highly trafficked web site. "

I think it's more to do with scale than performance; either way it's a legitimate concern.

"2. Security."

Legitimate concern.

"1. Create a background JavaScript process in the browser that sends regular heartbeats to the server. "

That keeps me logged in - see below.

"2. If you're worried about session hijacking -- and you really should be -- use a HTTPS protected connection. This is an absolute no-brainer for financial institutions of any kind."

I disagree it's a no brainer. You want clients to have certs as well; most don't.


So, interesting post, but you haven't factored in an important issue - people don't always log out of web apps. Think of it this way - imagine a site that has login, but no logout, as operationally that's how they tend to function. Does your argument still hold? I'm not sure it does as it's based on the assumption you want to keep people logged in rather than logged out. I think the sensible model tends to be managing security on a per resource/action basis and not as a global setting.

That's the why of browser session timeouts from the programmer's perspective. But that doesn't make it right. Far from it.

Bill de hOra on April 16, 2008 3:09 PM

@Paule Houle
i never said that timeouts are a good idea, in fact, i said they arent neccesarry.

And while i am surprised by the 24-hour-complaints, i still stand by my statement, that complicated forms are a problem.
I, as a user, am seriously annoyed every time a stupid shop makes a 5-Page form out of "...and now, send the stuff in the cart to this adress". Some of them even include mandatory surveys.
I would guess, that there's a huge amount of users, who never return, because the remember the shopping as too complicated.

keppla on April 16, 2008 3:19 PM

@HardCode
"The age old rebuttal, "What if the user walks away from his PC?" is so tired and so nonsensical. It would only make sense the day every malicious person waits the allotted 20 or 30 minutes before sitting at the PC of the person who walked away."
Most bank services deal in less time than that. Also, the chances of a malicious person getting to your computer within 20-30 mins is much lower than the chance someone malicious will pass it in the next hour.

@HardCode
"The issue can only be solved by end user discipline."
Aka "It is insoluble"
So you wash your hands of it, and if someone gets robbed, "It's not my problem, it's your fault." Conscientious.

"No 20 or 30 minute timeout or 15 minute workstation lock is going to prevent someone from sitting at the chair as soon as the legitimate user is down the hall, or out the door, or out of sight."
But it will stop someone from coming in 20 minutes later and doing the exact same thing.
The chances that there's a malicious user over your shoulder are small. The chances that one will use a public computer over the course of 2 hours is much much bigger.

Tom on April 16, 2008 3:27 PM

@Paul Houle
"Outlook and Firefox don't "time out". Microsoft Word doesn't "time out". Photoshop doesn't "time out". Amazon doesn't "time out". Google doesn't "Time out""
Does Google do something I'm not aware of with those tabs? A Financial Manager tab or soomething?

The only one of these that can do even a fraction of the damage that access to banking software can is Amazon, and they have a returns/cancellation policy. Also, they have the address where the ordered items were sent to, so they can easily track the actual items. All the bank will have is a record that the money was transferred into another account, which was then closed.

Tom on April 16, 2008 3:31 PM

For anything other than actual financial services the value of this level of security is highly dubious. The worst offenders seem to be web-based stores. Some are so bad, Verizon is a good example, that they will timeout and kick you back to the front page even when you're just browsing. Much more common is for stores to empty out your shopping cart with some ridiculously short timeout. Sometimes I like to take my time shopping, deciding which things I actually want, and sometimes I'll get pulled away in the middle of something, it's annoying to come back and have to start from scratch again.

Robin Goodfellow on April 16, 2008 3:40 PM

I wonder how many developers actually control the session timeout. I'm the application developer for a few commerce related web sites for my employer. There's no *code* in my application to time out sessions, which run on BEA Weblogic application servers.

However, the application configuration defines the timeout. The parameter was selected based on discussions with our IT security dept., the internal business unit for which the site was developed, our server admins, and myself. The selection was based on a combination of security issues (both financial and privacy related data) as well as server resources:

<session-descriptor>
<session-param>
<param-name>PersistentStoreType</param-name>
<param-value>replicated_if_clustered</param-value>
</session-param>
<session-param>
<param-name>TimeoutSecs</param-name>
<param-value>1800</param-value>
</session-param>
</session-descriptor>

Vic on April 16, 2008 3:54 PM

Note there is a difference between session id cookies and authorization cookies (at least for ASP.NET, but it's rubbish by all accounts, so I'm sure it's the same or better in php and ruby land)

That said, I'd say 1/2 of session timeouts are the result of poor/naive programming, and the other 1/2 is poor stakeholder decisions. Mostly the stakeholders are myopic and think their data is all important, but in reality nobody cares.

Fine .. my online Bank times out, and I think there's a good reason for that. It's about the only thing I can think of mind you.

For the rest of you, don't rely on sessions. They're evil. Sure shove a little cached state in there that you don't care about, and regenerate sessions on the fly. Then you can aggressively reclaim idle sessions and can still use load balancing. But don't rely on sessions for anything, ever.

For all you session time-out'ers, there's an easier solution. Identify critical actions and have users re-enter their password to proceed. Simple, and if you look closely, most of the big sites where the extra security matters do so.

Think of it the other way. Isn't it flawed to assume that just because clicks keep coming in, that it's still the same person? Also, as others point out, just because you didn't click doesn't mean you've left.

I've read a lot of the comments, and most are rubbish excuses. Web Browsers are not ATM's. Web browsers are not running cars. Web browsers are not waitresses. It's like using a hacksaw to remove a splinter in your finger. If you truly need security that badly, you shouldn't be using the web and relying on session timeouts.

RTFM on April 16, 2008 4:02 PM

I think the problem is not retyping you password, The problem for the user is Loosing-the-information-typed-in-the-form.

I normally choose the the following two-step session management

When the session times out (30 minutes), store the session info to disk (db) and keep it there for a 'long time' (Since my users mainly log in from internet-cafes, I choose 4 hours)

If they try to continue a session, (they make a new request / post new data)


If they try to continue a session after the re-auth timeout, but the session is still on disk:

> If They choose to 'be remembered' -> automatically restore there session and process the request / posted data.
> If they choose not to be remembered -> Store the request/data, reprompt them for their password (we know their username from the session data stored on disk)
- If they supply the correct password -> process the request / posted data.

If they try to continue a session that is no longer on disk:

> If they choose to 'be remembered' -> create a new session and Try to process the request / posted data.
> If they choose to not to be remembered -> ask for username and password
- If they supply the correct username and password -> Try to process the request / posted data.

just my 2 cents :)

Jack on April 16, 2008 4:04 PM

>>>
f0dder -- that doesn't help in the (extremely) common case of filling out a web form, walking away for an hour, filling out some more of the web form, and pressing "submit". All your data entry will be lost when you get redirected to the login.
<<<

Not necessarily. The browser did send the data in its POST-request, so it's up to the server to be able to connect the received data with the user who just logged in again. Creating a temporary cookie before redirection occurs doesn't look too hard to me.

And to take T.E.D.s example, something like that seems to work for some forums. Like him, I also tend to write a lot of stuff and rephrase it again and again, so the session expires, I get politely ask to submit my credentials again - et voilá, my posting appears. No data lost.

So according to my experience, there must be a solution for the "get me back to where I was" problem already. It's up to the stupid code-monkeys to implement it. ;)

Vinzent Hoefler on April 16, 2008 4:22 PM

A number of people have asked what kind of form could be so onerous that it requires a long session time. How about an ASP.NET web form with an upload component, which uploads the damn file into client-side memory even before you call the SaveFile() method to stream it to the server? Even a small file that loads relatively quickly could result in a session timeout.

Now take that same form and deploy it for users in the developing world, where hardware is often older and connection speeds aren't always exactly blazing...

protected static on April 16, 2008 4:49 PM

Keeping track of millions of session-id's?

Where is the problem, dudes? Binary search will do it! Scales incredibly well.

Keep the records that have been active over the last days in memory as a cache and put the older one into a database or whatnot.

Easy as that.

nils on April 16, 2008 4:50 PM

Session timeout problem for Corporate Apps.
This can't necessarily be done on the internet though. Here are some solutions:

1. HTTPS all the way for secure apps!
2. Keep user logged-in. (remember me via cookie, ip, etc.)
3. Store current view state (page id and field contents) in a cookie! (time based, as you type, etc.); encrypt the cookie!
5. Support concurrent access over the same session.
6. Support bookmarkable pages.
8. 8 hours (work shift) timeout.
9. Flash / Applets for state management.
10. I'm sure there's more!

J-F Poirier on April 16, 2008 5:33 PM

Instead of 'kicking' the user, why couldn't the site simply have the user reenter their password if they're away for more than x minutes, so as to revalidate and confirm their identity? I've had way too many situations where I simply can't find the content I was viewing again after getting booted by a site, and it's rather annoying...

Joshua on April 16, 2008 5:43 PM

I agree with Brett - Cross-Site Request Forgery (XSRF / CSRF) is the one compelling reason to time out a users authentication session. The longer users are left in an authenticated state, the larger the window is for CSRF attacks.

However, that does not mean the entire session needs to be destroyed after a short timeout - as Joshua says, simply ask the user to re-enter their password after a period of inactivity, like many internet banking systems do.

On the CSRF topic - always make sure state-changing actions (e.g. send email, transfers money) only respond to POST requests. It is trivial to cause CSRF GET requests using image tags etc, but tricker (not impossible) to force CSRF POST requests. For further security, require that the POST request contains a dynamic token which was included in the originating form - such as the users current session ID - to thwart one-size-fits-all CSRF attacks.

Sorry for the tangent, but the more web developers that are aware of this, the better.

Paul Annesley on April 16, 2008 6:24 PM

Strange nobody has mentioned rails, so I throw this out there:
http://dev.rubyonrails.org/changeset/6184

"Introduce a cookie-based session store as the Rails default. Sessions typically contain at most a user_id and flash message; both fit within the 4K cookie size limit. A secure hash is included with the cookie to ensure data integrity (a user cannot alter his user_id without knowing the secret key included in the hash). If you have more than 4K of session data or don't want your data to be visible to the user, pick another session store. Cookie-based sessions are dramatically faster than the alternatives."

Anon on April 16, 2008 6:29 PM

I want to say that https will not prevent session hijacking. Session hijacking is rarely done by sniffing the packets that go from the users computer to the server. This wouldn't be really fruitful, as there would be literally billions of packets to sniff. The most used methods are Cross-site scripting and session fixation. This way they will get their hands on the session id and can easily recreate the session cookie.

http://en.wikipedia.org/wiki/Session_hijacking#Methods

No type of encryption will be able to do away with this, as it is done on the users computer. So what other options are there? Since the hacker doesn't know the time of login for the user, it will be hard to log in right after they do. So a timeout will actually be the most effective way (other then asking for a password every time the user does something, which I would find even more annoying)

That said, for websites where security is not as high of an importance as a bank, sessions should not have to time out. Or you should at least have the "remember me" option. Where a new session is created automatically for you.

Thomas Winsnes on April 16, 2008 6:30 PM

Jeff, do you ever revisit these topics after the answer to your question is clearly explained in the comments?

XSS and CSRF are the reason why sessions should time out on the web. Yes, it'd be great if web security were better/easier, but the reality is that it currently isn't. You've left a lot of people saying "YEAH! WHAT JEFF SAID! THOSE WEB DEVS SUCK!" without truly understanding the problem at hand.

Unless you'd care to explain why XSS and CSRF can be ignored, it'd be nice for you to either update or post a new entry to clarify why session timeouts are a necessary "evil".

Brett on April 16, 2008 6:38 PM

Somebody might have mentioned this before, but I think a pretty low tech approach should be used as well. What about asking users at the very beginning with something like "Is the computer you are using now in public place?" If the answer is yes, use "paranoid mode" (eg. time out in 10 mins, as well as other security measures). If the answer is no, use "relaxed mode" (eg. time out in 3 hours).

The idea is to engage users with the concept of security right from the start, using language they can easily understand. Thus they can make qualified judgment, which we will then use in setting security measures for a particular session.

Paulus on April 16, 2008 6:43 PM

Having played with WCF in .Net 3.5 recently, I know that the above (Joshua's comment) is probably possible using Durable Sessions without inventing too many wheels yourself. This might be a good solution to the problem.

Jacques on April 16, 2008 6:47 PM

When I took over maintaining the internal HR application of a small size company, the first complaint i got from users was that when they upload a file for one particular employee, it gets saved to a different employee! A little investigation revealed this happens when the users remained idle for about 20 minutes after logging in and then trying to upload the file.. Considering the application is only used by 4 of the HR in the company, and they have their own machines, I simply extended the session time out to 2 hours, and have not got a single complaint yet.

http://ars.userfriendly.org/cartoons/?id=20080412 I was browsing a new web comic and it gave a funny side to the problem of session timing out..

Aravindan on April 16, 2008 7:20 PM

"A common practice to prevent sessions to be stolen, is to bind it to a certain IP address"

This is not even nearly safe. In a public setting, most shared computers will actually have the same external IP address, with router performing Network Address Translation (NAT).

Oz on April 16, 2008 7:39 PM

Use HTTP authentication! That way you don't even have a session to time out.

Meh on April 16, 2008 7:49 PM

@Foxyshadis
"Uh, yes, that's exactly what restaurants do. You get your drinks, when you're ready for more drinks or finally ready to start eating you can
signal or wait for the next time she shows up to order."
With the expectation of that fat tip you mention. And even with that fat tip, if you're not doing a decent amount of business, the staff and management will deeply resent your presence.

" I've had 4-hour lunches that went just like this, even in cheap places. That analogy is unbelievably stupid and irrelevant, but the fact that it's so wrong is just hilarious."

Service is service. Speed of service is paramount. If you are idly wasting resources that could be better used servicing people who are able to be timely and punctual about their use of the resources, you are a drag on the system.

"(Mapping food service onto the internet, are you insane?"
My sanity has nothing to do with the issue. Service is service. I bet you, too, are one of 'those people' who take cellphone calls at the register, or purchase 20 items plus tobacco and alcohol at a self-checkout lane.

"You just had better have a fat tip ready for staying around so long."
Which I would map to the higher development and service cost of a website or web application which would have 4-hour session times and increased security awareness.

I think this is an indicator of the general "ME FIRST & ONLY" type of thinking prevalent in today's modern, on-demand culture. People often fail to realize their part in receiving speedy, efficient, and excellent service. That part is understanding that you are not the only person being served by the system. This is much more transparent in say, retail or foodservice (you know when you are the only person in the store/restaurant), but it applies online as well. The server(s) must deal with many users at a time, not just you and you _only_.

I'd like to see Jeff revisit this issue after six months or a year of running stackoverflow.com . I'm guessing his view will be a little different then ;^)

Tarkin on April 16, 2008 8:05 PM

"but I've never once seen a session expiration message from gmail"

I have, many times actually, they just redirect you to the login page

Eber Irigoyen on April 16, 2008 9:50 PM

just some thoughts...

For preventing data loss in case of session timeout, it should be browsers responsibility to keep a copy of user data, if session expires, the user can hit Back button to get its composed email text.

it would be nice if we can have some standard Logoff and Lock buttons (web site level lock as we have for OS) in the browser - like we have close on top right corner.

Usman Shaheen on April 16, 2008 10:18 PM

The most stupid logout occurs in Sharepoint even though your session is identified through your Windows Active Directory Account. After some inactivity, it takes you to an intermediate page, where you have to push a link to reactivate your session. How daft is that?

GUI Junkie on April 16, 2008 11:22 PM

"Service is service. Speed of service is paramount. If you are idly wasting resources that could be better used servicing people who are able to be timely and punctual about their use of the resources, you are a drag on the system."

Vice versa, if it's done in a way that isn't a drag on resources, or is less of a drag than the extra money it generates, then it's worthwhile. Otherwise we may as well have no application at all, to free up all that precious cpu.

"My sanity has nothing to do with the issue. Service is service. I bet you, too, are one of 'those people' who take cellphone calls at the register, or purchase 20 items plus tobacco and alcohol at a self-checkout lane."

No, I just expect different service out of an unthinking, unfeeling machine than I would a human, and I can't understand this anthropomorphizing of the web server. You're the one basing your rationale on web application design on an industry example absolutely unrelated to the matter under discussion. I mean, if you're going to consider thirty minutes rude to a human server, then you may as well consider thirty microseconds as being rude to a web server, adjusting to its own time scale. Does it start to make sense how arbitrary the attitude is now?

Look at the shopping cart comment above and think back to how frustrated you got the last time you lost your cart over a session timeout.

See, I can write the code to transfer a session at timeout to another table, to prevent performance degradation, and load the session back into the main table on the next login (whether it's in five minutes or five years), in no time. Machines don't care if they have to hold onto things for long periods. I'm damn glad that I don't have a manager like you throwing such bizarre analogies at me when building applications - the clients are already bad enough.

Foxyshadis on April 16, 2008 11:38 PM

Sure, most anoying is loosing the data in form. Want it solved foor you on most sites word-wide in fiwe minutes? Use Opera and data entered to website will newer be lost by expired sessions.

Situation: you fill a form and send it when session expires.

On most sites, I need to enter login/password, press back button on my mouse, I see the filled in form and just click ok. Done.

On ugliest sites wordwide I press the back button twice, see the form with data filled, copy them to notepad, navigate to that form again and paste them field by field.

Tomas Tintera on April 17, 2008 12:02 AM

There is also the case of timing out due to locking other resources than the server hardware. For example, in a web shop you don't want one visitor to lock some items that could be bought by another visitor whilst the first visitor was gone doing something else.

Adam on April 17, 2008 12:31 AM

A banking application is maybe just one exception why you should have a time out in a web application. A bank wants to cover itself and be sure that your money can only be transferred by you when you are logged in.

I only want to loose my session if I close my browser. For the rest, keep my application alive.

Michael on April 17, 2008 1:08 AM

There are so many applications you can get timed out of especially if you are using secure networks.

It is a pet hate of mine to have log back into half dozen networks/applications every time I leave the computer for half an hour or more.

Cracker http://www.dragonlaseres.com

Cracker on April 17, 2008 1:13 AM

No timeout = ability to do a DOS attack on many sites.

One example: an airline. You book a seat, take the transaction to teh credit card input stage, and then walk away. That seat -- on a specific flight, leaving later today -- is being held for you, pending you completing the transaction.

Do the same on a couple of dozen PCs for the same flight (or the same PC via an anonymising service).

Result: you have prevented the sale of half the seats in an otherwise busy flight.

Harry on April 17, 2008 1:17 AM

I also agree with Benedict. Sessions go against the stateless principle of HTTP and REST and should be avoided.

Asbjørn Ulsberg on April 17, 2008 1:28 AM

I usualy make the page ask again for the usr and passwd and when they are correct then the user is taken to the place where it was "last seen"
This has a drawback if you have some sort of form that was not submited...it will be cleared...but better than nothing :)

mardicas on April 17, 2008 4:17 AM

My bank, HSBC, recently introduced a neat feature into its online banking. If you haven't done anything for five minutes, it pops up a window asking you if you wish to stay logged in, with a one-minute countdown. That way you don't need to worry if you have to leave your computer alone, and if you need the session to stay alive (say because you're working something out to do with your old transactions onscreen) it lets you do that.

Earle Martin on April 17, 2008 6:28 AM

For financial companies PCI Compliance requires that all websites have session timeouts of no greater than 15 minutes. Even if everything is HTTPS we still have to kill the session.

However to be Section 508 compliant we also have to give a pop up warning the user their session is about to expire. So the user experience is one of many annoying alerts instead of many annoying logins.

I dream of a day when a usability expert is included in all of these compliance discussions.

Dan on April 17, 2008 6:30 AM

> And, besides this, i think the real problem here is, that there are
> forms which are that huge and painfull to fill that the user takes > more than 5 Minutes.
> What are they for, doing the tax declaration?

How about a web posting? Perhaps you are sharp enough to craft a readable web post you are satisfied with in 5 minutes or less every time. A lot of us are not.

It amazes me how many people here are missing the point. Sure there are situations where its a good idea to reauthenticate the user every now and then. (Almost) noboby's arguing that. But I *don't* need that level of security in a message board, or a web game. Just have a little sense. If someone in my house walks by my PC and posts something stupid in my name on the WoW forums, I'll just go smack them around until they get the idea not to do that anymore. I don't need your help to stop them.

There's an underlying issue here I think that relates to security. I've seen it in lots of other spheres too. I know we developers tend to think our programs are Very Important, because we devote large parts of our lives to crafting them. But at some point we really have to *get over ourselves*.

Not everything our programs do is worthy of retinal-scan biometric security access. Nobody wants to hack your user's crappy game sessions.

Not every program's sources are so innovative that they need to be zealously shielded from prying eyes, and refuse to even install if a debugger is installed. More likely if they saw your source code your customers would laugh themselves sick and your competitors would go broke trying to copy it and get it to work.

Not every program is so sensitive that it needs a license manager and a $3000 dongle system that has its own internal clock (so that cretin user can't just set the clock back when the license expires). If someone makes a bootleg of your recipe-management program, the nation's terrorist atlert system won't go from yellow to orange. Honest.

So *please* have a sense of perspective, and be nice to your poor users.

T.E.D. on April 17, 2008 7:22 AM

I wonder if we should, as an industry, look at this in a totally different light?

Instead of expecting users to accommodate our security needs let's do it ourselves. Instead of assuming "everyone does it this way" let's make room for every use.

How? My idea is to model it more like the physical world. As Neil said, you don't leave your keys in your running car when you go into the store so why leave your bank logged in when you walk away from any computer that doesn't have physical security such as a cafe? (If the cafe locks you out when your time is up then do the important stuff first and surf the news at the end so if it locks it's no loss)

ATMs have limits. Mine only allows $200 per day to be withdrawn which limits the bank's loss in case of fraud. Why not the website? Any bill payment or fund transfer over $X requires a login. Queue up the 5 bills you have to pay and put in your password again to commit the payment and it's all good. It's a pain to have to do the extra password but it's what we are used to - if it's over a certain amount you have to prove yourself. I could walk into my bank with a check for $30 and they probably wouldn't even ask for ID. If it was $30,000 they would want a fingerprint and a DNA test to prove who I am. (ok, I exaggerate but you get my point.)

Also mentioned is that no session timeout is really all that safe. If I'm at a cyber cafe and my time is up there is a great chance that someone is right there ready to use the system. No 5 minute timeout will help there. It's especially true in the more poor places such as West Africa where practically no one has a computer but many people use one at a cafe.

In fact, because I don't know the owners of the cafe and how the system is secured, I'd be hard pressed to even use a public terminal for sensitive actions such as banking... but I'd surely be as careful as possible if I *had* to do it there. Don't you watch over your shoulder at the ATM? Mine has mirrors and it's my favorite feature - I can see if someone is looking over my shoulder or raring back with a fist aimed at my head.

It's time that we developers take the stance that in today's environment we should accommodate the end user's needs and bend to their habits as much as possible. We are no longer in the elitist 1970's where we are computer gods and you'll do it our way and like it. Originally the telephone was only one style. Now there are small phones, big phones, lit phones, phones with monstrous buttons, amplified phones, etc. As they became commonplace they adapted to the needs of the users - it's time for programs to do the same.

Gee, this is getting a bit long - I sure hope my session doesn't time out. lol

Jim Sewell on April 17, 2008 8:13 AM

And I thought I was distractible! What kind of ADD must you have to walk away for hours or days from something like banking? Timeouts do suck, though.
I don't leave my PC on unless I am actually working on it. I even turn off the modem and other stuff most times like speakers and so on it saves a lot of electric. I guess i'm not much fun for launching attacks even if i was hijacked. Never could be sure if i'd be on. I took the safety test and it says my PC is locked up tighter than fort knox, yet i still feel a little insecure banking online no matter what i do.
I support the right tool for the job approach, make things as secure as they need to be, no more or less. That would save some of the daily frustration.

D. on April 17, 2008 10:07 AM

For all those (including myself) who are paranoid about the having all the data available on the screen for anyone to see, we can implement a simple "lock screen" layer on top of original layer where user would need to re-authenticate him/herself after x minutes of inactivity.

After authentication (which would be a ajax server call), the lock layer would go off, and user is back to his/her screen with all data intact.

Vijay Dharap on April 17, 2008 11:12 AM

Another reason for session timeouts, that you didn't mention, is shared computers. Possibility of leaving a banking page open and forgetting about it in a place like internet-cafe _calls_ for expiring sessions.

dali_bude on April 17, 2008 1:09 PM

[quote]
The age old rebuttal, "What if the user walks away from his PC?" is so tired and so nonsensical. It would only make sense the day every malicious person waits the allotted 20 or 30 minutes before sitting at the PC of the person who walked away.

*snip*

HardCode on April 16, 2008 11:08 AM
[/quote]
Very true and, IMO, the best arguement for user education. You can provide them a faux sense of security with session timeouts or you can educate them. In the meantime, the least you can do is make the timeouts non-intrusive to their experience with your web-app.

TopicSlayer on April 17, 2008 3:31 PM

Security through wishful thinking and misguided notions.

Since this is allegedly a forum for tech-minded folks, lets make the differentiation, because a lot of the comments talk about sessions in the abstract, waitress analogy that has nothing to do with technology or with what a session really is.

A quick recap:
FTP is stateful. Once a user connects to an ftp server, they authenticate and a connection stays open for the length of their visit. If you disconnect / close / lose the connection, you have to re-authenticate the next time. FTP servers routinely disconnect idle connections.

HTTP is stateless, so a web app has no natural means of identifying one user to the next. A connection is made to a web app to retrieve a document. Interactive, static, ajax, gif, jpg, mp3. whatever, it's still a document and only a document.

Ah, but then came HTTP cookies, little chunks of data that are persisted by the client. Cookies are given names, contain data, and have lifetimes (they are essentially persistent with some variations). All the cookies for a website are sent on each request (for a document) and returned on each response (the document data).

Authentication (cookie) - when a user proves to the web app who they are, the web app gives them an authentication cookie. This enables the web app to identify the owner without re-requesting authentication on every document request. There's no universal authentication cookie, it's just a 'special' cookie that the web application knows about. (forgive me for ignoring other authentication methods)

So, given that background ...
Session - typically referred to as data stored on the server for each uniquely identified user. From the perspective of the web application, it's globally accessible data for the user that survives document requests, and gives the illusion of 'state'. Bad programmers often chuck all sorts of junk into the session naively thinking it makes things easier for them (shopping carts, recordsets, etc). Early / basic implementations of the session just store the data in normal memory.

Now, a server has an upper limit on memory available. If sessions are used, the number of unique clients it can service is directly proportional to the size of session data. Back in the day, when the only session was in-memory, people realized after their servers fell over that it wasn't a good idea to hold onto this forever and decided that perhaps expiring sessions was a good idea. How long though? A question that was never answered correctly.

Another issue with using sessions and in-memory session data is that it doesn't scale out, only up. I.e. you can only get 1 massive computer, a single point of failure, and far more expensive, instead of adding farms of low end servers that can use cheaper components, and only adding more computers to the farm when necessary.

While scaling out is still better, other smart people have come up with other ways to (ab)use session data, but still have it scalable. I'll pick on ASP.NET just because I'm an old droid and can no longer grok php/ruby or linux. Sessions State Servers, Sql State Servers, and even the ability to create your own home-brew state server. All can allow farms of servers to act like they share the same old in-memory session data. Load balancers can also sustain the illusion by using sticky sessions (rerouting the same user to the same machine each time) But I digress, these are all band-aids provided by vendors to allow sloppy programming practices to continue.

The term session timeout stems from when the sessions were in-memory and sessions NEEDED to timeout. As pointed out above the world has moved on. Sorry for shouting but SESSIONS NEED NEVER TIMEOUT. Not that you should use sessions anyways, lazy programmer in the corner picking your nose, pay attention.

So, for the love of Pete, don't use sessions. Don't expire sessions. Don't abuse and rely on sessions with the misguided notion that they are some sort of security feature.

"Session hijacking" can occur anytime, so relying on timeouts isn't a solution. It only decreases the likely attack window, but that's about it. Do your homework.

Finally, what many people are alluding to is timeout of the authentication cookie (sometimes also called a ticket). As the smart people point out, when the need arises, mimic successful websites who obviously paid someone to do some usability testing. Amazon remembers you indefinitely, but does ask you to authenticate when you go into places like credit cards, account details, etc. Do the same. Force a user to re-type their password when necessary.

Most of the time people don't want to be logged in as someone else. Most of the time people turn off their computers when they're done. Most people don't live in dodgy internet cafe's. You can't force security on people.

i.e. Insurance company selling online stuff.
- buy new policy - OK ask to verify on 'buy now'
- view policy - No, who cares. It's probably just boilerplate text in a pdf anyways.
- cancel policy - OK verify, it likely matters
- submit claim - OK, probably a good place as well
- view account - nah
- edit account - OK, also a good idea.
- send a question to online support - again, who cares.
- other random surfing around site - who cares. Everyone has insurance policies, so what's the secret?
- likelihood of logging in at a dodgy internet cafe? 0.01%

Now before someone complains that 'I don't want to log in every time I do something' think of anyone but the tester. In most normal usage scenarios, a user will only get prompted once or twice on their visit.

In the banking scenario, fine. It's not sessions though, it's inactivity. Sit idle for x minutes, warn user. If no response 'log out'. Note that you can't rely on people to log out either, so that authentication ticket is sent to the server the next time, and it still needs to check when the user last did something. If that something was > x minutes ago, force them to login first. Does that mean they can't be at the same place they were before?

You don't have to keep them logged-in forever. Even Google makes you re-authenticate once a month regardless of how often you use their service.

One last word on Internet Cafe's. Reputable / decent one's i've been to reset the OS from scratch every time someone logs out. If you're in some dodgy place using the internet, how can you even be sure there aren't keyloggers present? what about video camera's recording what you type? You'll never be secure in those situations.

Think a timeout's gonna help you there? Is a timeout going to stop your kids from unplugging the cable and delving into browser history (hint most browsers will give you the last version of the page, which is still all the pages you visited while preciously logged-in). Your rubbish timeout doesn't help there either. Maybe you can prevent this in some browsers, but it's not a universal feature, so like everything else in web app land, you program to the lowest common denominator.

Sessions are evil. Session timeout is evil. If you don't get that by now, change careers.

RTFM on April 17, 2008 4:30 PM

My view on session timeout is, if you have very good h/w (like google) for your server then you can afford to keep the session for a long even if user is idle, and if you don’t have that kind of hardware (mainly RAM), you must use the session timeout. You can’t just make processing of other active members slow because of the idle users. Performance will surely go down as when RAM is over, then page file on disk will be used and overall performance will go down.

Anup Daware on April 22, 2008 8:17 PM

Typically apps don't store state in cookies because they can be easily tampered with by a malicious user. The alternative is to store session data in the app, which generates overhead, hence auto-logging people out.

My solution in some applications is to generate a crypto keyed Hash Message Authentication Code (HMAC) of the cookie content and store that in the cookie.

Then, when the cookie is presented back to you, check the HMAC. You can now safely store all session data in plain text in the cookie, and need keep no state in the app.

Oliver on April 23, 2008 5:09 AM

I am a database Administrator.And for non trivial web apps that communicate with a database having sessions extend over hours and be resumable from where they were up to,implies locking records for hours in the database.This kind of thing really impedes other transactions and is another reason why session time out is sensible.

If it didn't occur the same person may well be trying to get back in and not be able to, only to find their records still locked by their previous session!!!

Locking records in database for extended periods is a recipe for disaster. Say i wanted to update everyones salary by 10% and I cant, because all their records are constantly locked.

Database programmers try to ensure concurrency by by NOT allowing
locks to persist for extended periods.

If their "sessions" were kept open ( but not their database locks)
they would still need to re initiate these transactions to try to re aquire these ( records &)locks in anycase. Besides, if in the mean time data has changed,you shouldn't be merely trying to push through their transaction as the criteria upon which they have acquired these lock and records may have changed and would lead to a different or unwanted outcome or and may well mean that they dont want to proceed with the transaction any longer. ie. it is no longer wanted or needed
eg buying a book, if the mean time the price has gone up, or a better book become available - they may no longer want to buy it,or it may be out of stock. They should have to ( & not unreasonably re initiate the whole process ) - I believe most people would want and expect this.

If you want to kill performance and user satisfaction and basically kill the app - allow sessions to hold locks indefinitely.


Mark on April 24, 2008 8:09 PM

I don't recall the URL of the blog entry, but some time ago I stumbled over a new functionality in a well-known AJAX framework, which' name I don't recall either. It offers some kind of "screen-saver" overlaying the page/application with a modal dialog, requesting to re-authenticate after a time-out with the password. When done so, modal dialog disappears and the user can continue working as when he left.

Indefinite session time out makes no sense, but usually a day or so, at least for interactive apps, makes sense. The question is whether you want to pay for it to set up the resources to hold the sessions long enough.

Cheers!

Ralf on April 27, 2008 5:21 AM

@one of Paul Houle's comments, the "10-minute timeout", &c.:

The library catalog Voyager does put ridiculous resource demands on a server with its web interface (RAM demands increased by a factor of 5 from one version to the next), agreed. But it, and similar software, consist of far more than that front end: It's like an iceberg, with much happening where the user doesn't see it. Gotta share resources, and many libraries aren't keen on buying the amount of RAM needed to support hundreds of long-running sessions, precisely *because* the user doesn't see it--how can you justify it to a university administration, for example? BTW, the timeout doesn't have to be 10 minutes: Some Voyager libraries have a timeout as short as three minutes and others have timeouts of 30 minutes (or more).

But as a librarian, I'm very much conditioned to think of the user's privacy, and I want to protect your privacy EVEN IF YOU ARE NOT LOGGED IN to the software. So I want that library catalog session to time out, because it isn't anybody's business what you were looking for in the catalog.


jc on April 30, 2008 2:52 PM

Some of you punters still don't get it. Relying on session tear-down is a bandaid to bad coding. Relying on session data and having that reliance visible to the user, at all, is bad practice.

If you have users, you store things like shopping carts, preferences, etc. You should store these indefinitely, or at least until you can tell that a user is never coming back. Storage is cheap. You would never hold any of this in 'session' unless you're an idiot. Newbies take note! What looks easy is a recipe for disaster.

Locking: No self-respecting developer should hold a database lock open between requests, let alone minutes and hours. Unless you only make single person websites, this will never scale, ever. @Mark, I pity you for the people you work with. Non-expiring sessions does not imply locking. Retaining a db lock over 1 request implies bad coding. Smells like limburger cheese left in a heating vent for a few months.

Sessions are a bad smell. You don't need in-memory 'sessions', ever. Read my previous post about what a session is. In God knows how long I've been writing websites, there's always a better, more scalable way.

Session are not the same as authentication timeouts. Most self-respecting frameworks let you re-authenticate without losing what you're working on. It's a usability thing, but maybe you just don't care about writing correct websites.

RTFM = READ The Fscking Manual

RTFM on April 30, 2008 10:02 PM

On a project that I worked on, we actually had some fancy stuff that would allow you to "resume" after a session time-out error. In summary, when you would make a request to the server after your session had timed out, you would get a lightboxed login screen. By filling the form out and submitting, the application would attempt to re-execute the request that you had originally submitted (I think the request was serialized as a hidden field on the lightboxed login form). This worked for any XMLHttpRequest. So, you could half-fill a form, go away for a year, and come back to fill the rest of the form. When you click "submit", it would ask you to authenticate, but would then successfully post your form (as long as we hadn't changed the code on the back end during your hibernation).

This was reasonably easy because we were using a custom MVC library on the server. Granted, I'm not suggesting that you develop or use a custom MVC library (ever!), but that's what we had and so we (ab)used it. The overall experience was slick. Well, I think so anyway.

Perhaps a better solution to the problem is coming with HTML5 and client-side storage. Rather than store session on the server, it might be possible to store everything you need to know on the client (as long as you validate it all before you use it on the back-end).

Dan on May 10, 2008 10:27 PM

Use SSL client certificate instead. It is secure as SSL. The process of logging in is hidden from user, you don't see forms, don't press a submit button and such a crap, don't reload a page, are not redirected, nothing. Major browsers support SSL client certificate. *It's a shame that it is not used on web-sites.* You can even benefit from global authorization (like OpenID), because you can *safely log into different sites with the same client certificate*.

beroal on May 12, 2008 6:16 PM

I like an IFRAME with a page (say HeartBeat.aspx) that serves itself as an empty page with a meta refresh... as long as the user is on any page, they keep chatting with the webserver to keep the session alive. Makes 5 minute cookies a reality.

http://www.codeproject.com/KB/session/Session_Defibrillator.aspx

Marc Brooks on May 19, 2008 3:21 PM

Isnt this a simpler way to keep session alive? Use SetInterval, then include the EnableSession attribute on your web service method?

window.setInterval(KeepAlive, 300000);

[WebMethod(EnableSession = true)]
public void KeepAlive()
{ return;}

Rob Kraft on October 7, 2008 8:28 AM

What if Cookies are turned off- I never had solution for Gmail with IE - Accidentally I turned off my cookies & now I am never able to login on Gmail through IE - btw I don't like that browser always :) Mozilla is perfect for us.

Sunny on October 29, 2008 11:57 PM

I have been timed out by Verizon using e-mail. Why am I not given a clue like " 1 min. left ). To loose a letter I have typed carefully, is not funny or customer friendly. At the time of installation of service I was not told about time-out nor was I given a term of service with such info. If Bell telephone in 1948 could tell a long distance customer ther was 1 min. left on a 3 min. call surley someone can come up with a notice to the user. Verizon is not a customer service friendly provider of service. They suck.

Pamel on January 21, 2009 7:33 PM

In fact there is a fairly simple solution to the problem of preserving context after session expiration. Dan on May 10, 2008 10:27 PM has something nice, but there is a simpler approach that resides entirely on the server and therefore doesn't require XMLHttpRequest or indeed any Javascript at all.

In short, it involves never changing the URL, even if you need to display or process a login form, and always adding to the login form any post your page has received, using hidden fields.

A well crafted, general-purpose include module (or equivalent technology) can handle this for all (form processing or plain GET) pages in your web application, so you don't have to implement this solution on each of them individually. The same goes for the processing of the login form: every page should potentially be able to process it (the authentication logic should go into an include that every page can use if a post is detected and it contains the login and password fields).

The only elements of your form that will need special attention are file upload fields but there are solutions for these, too.

I have been using this for years, and it works perfectly. After the user is authenticated, whatever he was trying to do is performed.

Andrea on January 23, 2009 1:43 AM

I was wandering if it would be possible to create me a simple program to stop my online banking logging me out or do you know of such a program already in existence. Maybe just tell it to activate the browsers refresh button would do fine. I am not a programmer at all yet so i wouldn't be able to create this myself.

thank you so much in advance

jsmith07611@gmail.com

jason on January 25, 2009 1:05 AM

@jason:

For Firefox: ReloadEvery.

https://addons.mozilla.org/en-US/firefox/addon/115

Andrea on January 26, 2009 6:00 AM

Good Day. Do not be awe struck by other people and try to copy them. Nobody can be you as efficiently as you can.
I am from Mauritius and learning to speak English, give please true I wrote the following sentence: "If you are looking for the best online travel agency, then you just succeeded by finding sas airline tickets."

Thank you very much :P. Kabibe.

Kabibe on April 20, 2009 11:35 AM






(no HTML)


Verification (needed to reduce spam):


Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved.