You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Avoiding Unwanted Session Timeouts

Avoiding Unwanted Session Timeouts

Even the most productive and effective application can be rendered useless by a poor user interface. Before we start, I want you to consider, for example, the following frustrating scenario....

Joe is a salesperson at a company that uses a Web-based online expense report system. It's the end of the month, so he logs into the system and starts filling out his expense report. Many fields need to be filled out, and in the middle of entering the data he goes searching for receipts and other paperwork. For security reasons the system is set to timeout his session if 15 minutes go by without any "activity." After working on his expense report for 25 minutes and having his session timeout without his knowing it, he presses the save button. The application has timed out and he's forced back to the login screen.

Joe isn't quite sure what just happened, so he logs in again and goes to his expense report. Of course, none of his work was saved and he curses at the "stupid program." He starts to redo his expense report, searches through a mound of paperwork and again fills out dozens of fields. This time it takes him only 16 minutes but when he presses the save button the system has again timed out his session and he's forced back to the login screen.

Angry and dejected, he calls Jane in the IT department. She quickly walks him through saving an expense report (taking less than 15 minutes) and of course it works just perfectly. Joe tries in vain to explain to her that he tried to save his expense report twice and both times it wouldn't save. When Jane gets off the phone she thinks to herself, "Typical stupid user." Joe is thinking "Typical stupid program." Frustration all round! (See Figure 1.)

The Problem
Developing applications for a secure intranet or extranet almost always leads to the idea of a session. Since HTTP is a stateless protocol, the ability to authenticate a user with a login is often tied to sessions. ColdFusion makes much of this easy for developers with its session-scoped variables. But they leave a security hole: if Joe logs in so his status is saved in a session variable then leaves for lunch without logging out, anyone can come in and access information using his login.

The accepted solution to this problem is to timeout the session. This means that the system terminates the session and forces Joe to log in again if there hasn't been any activity for a specified number of minutes. The problem with this solution is that activity must be server-side activity since the session is tracked on the server. By this criterion, filling out form fields doesn't count as "activity" since it doesn't include any communication with the server.

It would be nice if we could somehow warn Joe that he is about to timeout and offer him an opportunity to save his work. CF can't do this on its own since it's a server-side scripting language. Action may be taking place on the client side that the server and CF are not aware of.

JavaScript: setTimeout
JavaScript is a scripting language that runs on the client's browser and works well in conjunction with CF. Javascript has a powerful function called setTimeout (don't let the name fool you, it has nothing to do with the session timeout we've been discussing). The setTimout function allows you to run a piece of JavaScript at a specified interval:

setTimeout(JavascriptCode, Timeinterval);

The JavascriptCode is often specified as a function and the Timeinterval is specified in milliseconds. The following code will run the ShowHello function in 5,000 milliseconds (five seconds):

<SCRIPT Language="Javascript">
function ShowHello()
window.alert("Hello, world!");
setTimeout(ShowHello()', 5000);

We defined a function called ShowHello and then use the setTimeout function to run the Show- Hello function in five seconds. Neat, but the real power of the setTimeout function is that you can have the specified function reset the Timeout function so that the specified function is called continually.

<SCRIPT Language="Javascript">
function ShowHello()
window.alert("Hello, world!");
setTimeout('ShowHello()', 5000);
setTimeout('ShowHello()', 5000);

After the first five seconds the ShowHello function runs, and pops up an alert that says, "Hello world." After you press the OK button, the ShowHello function resets the setTimeout function to run itself again in another five seconds. This continues, with the result that every five seconds an alert pop ups. This works just like a timer. Hmmm, it seems we could use this same technique to help solve Joe's problem.

The Solution
By using a combination of Java-Script and CF, we can develop a custom tag that warns users that they're about to timeout, giving them a chance to save their work and refresh the page before they lose their information. It will have three inputs or attributes:


  • The number of minutes that the system is set to timeout a session
  • The number of minutes ahead of time that we want to warn the user (the threshold)
  • The actual warning message that will be displayed

    Using the <CFPARAM> tag, we define the attributes of the custom tag and set a default for each of them:

    <CFPARAM Name="Attributes.TimeOutMinutes"
    <CFPARAM Name="Attributes.Warning-
    <CFPARAM Name="Attributes.Warning-
    Default="You will timeout in
    #Attributes.WarningThreshold# minute(s)!">

    The next step is to set some global JavaScript variables. We need to know the time the current page was first accessed, as well as the threshold time. Using time in JavaScript is much easier if everything is converted to milliseconds, so the first thing we do is get the current Date/Time and convert it to milliseconds. Then we convert the Attributes.TimeOutMinutes to milliseconds by multiplying by 60,000 and then adding the result to the current time. This gives us the number of milliseconds that represents the exact time before the current session will timeout. We also convert to milliseconds the Attributes. Threshold, which is in minutes.

    <SCRIPT Language="Javascript">

    // Global variables
    StartTime = new Date();
    StartMils = Date.parse(StartTime.toLocaleString());
    TimeOutMils = StartMils + (60000 *
    ThresholdMils = 60000 *

    The next step is to create a CountDown function that will run every 10 seconds and check if it has reached the given threshold. We already learned how we can use JavaScript's setTimeout function to create a timer. The first line of this function clears JavaScript's Timeout mechanism just to be safe. Remember, although the names are similar, JavaScript's Timeout functions have nothing to do with the session timeout that we're dealing with. They are simply functions that we use to setup and run a piece of code every x number of milliseconds. We'll use this later to run CountDown every 10 seconds.

    Next, we get the current time and convert it into milliseconds to calculate how many milliseconds are left until the timeout occurs.

    function CountDown()
    CurrentTime = new Date();
    CurrentMils = Date.parse(CurrentTime.toLocaleString());
    RemainingMils = TimeOutMils - CurrentMils;

    Once we have the number of milliseconds until timeout, we can compare that to the threshold milliseconds. If the number of milliseconds until timeout is less than the threshold milliseconds, then we display the warning message. If we haven't reached the threshold then we use JavaScript's setTimeOut function to run our CountDown function again in 10 seconds, thus:

    if(RemainingMils < ThresholdMils)
    timerLoop = setTimeout('CountDown()', 10000);

    Finally, we have to remember to run the CountDown function for the first time to set everything in motion and start the timer. Normally, you would call it in the <BODY> tag's onLoad event, but since we're writing a custom tag, we don't want to rely on the tag's user to remember to add it to the <BODY> tag. So we call it with inline JavaScript before closing the script, as shown here:

    // run CountDown for the first time

    Save the preceding code as c:\cfusion\customtags\TimeOutWarning.cfm and you can use the tag by simply calling <CF_TIMEOUTWARNING>. For testing, add <CF_TIMEOUTWARNING WarningThreshold="1" TimeOutMinutes="2"> to a CF page. About a minute after loading the page, a warning will pop up, "You will timeout in 1 minute(s)!" (See Figure 2.)

    As developers, we must always be conscious of user interface issues. As the scenario at the beginning of the article shows, user interface is the difference between an application that's usable and accepted and one that's unusable and the cause of frustration. Often the most productive and effective application is rendered useless because of a poor user interface. This custom tag is one way that you can help improve the user's experience and it only takes one line of code to implement.

    Now let's revisit our original example (see Figure 3).

    This time Joe logs in and begins to fill out his expense report. While shuffling through his receipts, he hears a beep. Looking at the screen he sees a warning message and realizes he's about to timeout. He presses the save button and continues shuffling through his receipts. Once he's done, he submits his expense report for approval and he can now actually get some work done. He no longer thinks "stupid program." Instead he appreciates the way his expense check is processed within three days.

    Throughout all of this, Jane in IT is able to play Solitaire without interruption.

  • More Stories By Daniel Jean

    Daniel Jean, CTO and cofounder of Galileo Development Systems, a provider of Web-based software solutions for the consulting and
    contract staffing industries, has worked in the client/server and Web development industry for 10 years.

    Comments (1)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

    IoT & Smart Cities Stories
    @CloudEXPO and @ExpoDX, two of the most influential technology events in the world, have hosted hundreds of sponsors and exhibitors since our launch 10 years ago. @CloudEXPO and @ExpoDX New York and Silicon Valley provide a full year of face-to-face marketing opportunities for your company. Each sponsorship and exhibit package comes with pre and post-show marketing programs. By sponsoring and exhibiting in New York and Silicon Valley, you reach a full complement of decision makers and buyers in ...
    While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
    The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
    Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
    The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
    Rodrigo Coutinho is part of OutSystems' founders' team and currently the Head of Product Design. He provides a cross-functional role where he supports Product Management in defining the positioning and direction of the Agile Platform, while at the same time promoting model-based development and new techniques to deliver applications in the cloud.
    In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
    There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
    LogRocket helps product teams develop better experiences for users by recording videos of user sessions with logs and network data. It identifies UX problems and reveals the root cause of every bug. LogRocket presents impactful errors on a website, and how to reproduce it. With LogRocket, users can replay problems.
    Data Theorem is a leading provider of modern application security. Its core mission is to analyze and secure any modern application anytime, anywhere. The Data Theorem Analyzer Engine continuously scans APIs and mobile applications in search of security flaws and data privacy gaps. Data Theorem products help organizations build safer applications that maximize data security and brand protection. The company has detected more than 300 million application eavesdropping incidents and currently secu...