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
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
    IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
    The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
    Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
    Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
    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 settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
    To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
    In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
    Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...