Managing Sessions In CF Ajax Applications
Everyone is likely familiar with standard application logic for managing authenticated sessions with ColdFusion. Typically you do some sort of check inside your Application.cfc file (usually in onRequestStart()) and if the current user is not authenticated (or there session has timed out) you redirect them to a login screen. Nothing new there, but when you think of the nature of an Ajax application you realize that there is a fundamental issue with that concept. What happens if a cfdiv were to be refreshed and the users session has timed out? Well, likely your cfdiv would then contain the results of the redirection (maybe a login.cfm template), but that may not be the 'prettiest' solution depending on your application.
So I put together a quick application to demo one possible solution. The basic concept this:
- Log a timestamp of the last 'hit' by a given user in their session
- Create a simple facade that looks at the time difference between the last hit and the current time
- Create a ajax proxy to query that session facade
- Make sure the proxy request does not update the 'last hit' - otherwise your session will never time out
- Run a call to the session facade (via the ajax proxy) on a set interval
- Evaluate the inactivity period, if in a 'warning' period (say between 15-19 minutes) display a modal window warning the user.
- If the user chooses to extend the session, ping the session facade which will update the 'last hit' variable.
- If the inactivity is beyond the session timeout (I usually go with >= 19 minutes display a modal (non-closable) window telling them the session has timed out
I have a demo online here. If you open the demo and wait longer then a minute you'll be warned. Longer then 2 minutes and you're logged out. Full source is attached to this entry. As always, feel free to post questions/comments.



During the last weeks (and coming weeks) I'm working on a application using the CFajax stuff exclusivly. Thanks to the blogging of you, Dan Vega, Ray Camden and a few others the process have been easier than it would have been leaning on the CF docs only.
What you are showing of here is something that was on my "to solve" list. Excelent!!!
Thanx a lot for this, and your other posts on the topic.
on my last cf ajax app, I made use of onbinderror. Just use cfheader to send back an error code when session expired.