AdobeStock_455007340

Flex And Session State Management

Home » Flex And Session State Management

One question that keeps coming up when presenting Flex (especially to those porting existing apps to Flex) is “how do I maintain session state in a Flex application?”.
This is an interesting question. Interesting less because of the problem itself, and more because it demonstrates just how webified we have become. So, let’s step back a bit …
Web apps (powered by ColdFusion, ASP, JSP, PHP, or just about anything else) often need to maintain session state. If a user logs in you need to maintain that information so that it persists across requests or else the user will be prompted to login on each and every request, if a user puts items in a shopping cart that cart must be stored within a user session or else the cart will be empty each time the page changes, and so on.
The reason that session state needs to be maintained is because the web is stateless, each request stands on its own two feet, and within a request there is no awareness or knowledge of prior requests. Each time a page is requested a connection to the server is made (often multiple connections) to retrieve the needed elements, and then that connection is broken. This allows HTTP servers to respond to lots of traffic (far more so than if connections were always kept open), but the down side is that web pages are not aware of any activity performed by the same client previously.
To allow data to persist in the stateless web we’ve grown accustomed to taking advantage of what might be best described as a hack. In web apps, data to be persisted is stored on the server, so that it’ll be present on subsequent requests. Of course, this necessitates that there be a way to associate a specific block of data on the server with a specific client, and so web applications (or application servers) create session identifiers which are sent to the client, and which must be sent back to the server on every subsequent request. These identifiers are most frequently stored in cookies or embedded in URL tokens or hidden form fields. But where they are stored is less important then the fact that they are needed, and must be submitted from the client (the web browser) back to the server on every subsequent request or else session state will be lost.
Life was not always this convoluted, things used to be simpler. Desktop applications and client-server apps never had to rely on state being maintained on the server. In those apps the client itself is stateful – it is not a set of loosely coupled scripts sitting on a server, rather it is an actual application running on the client, an application which does not completely reload when items are selected or clicked on. Requests are indeed made back and forth between the client application and the server as needed, but the client is always present and always running. And so preferences can be stored on the client, as could shopping cart contents, as could login details.
In other words, session state management is not preferred behavior at all. Rather, it is an unfortunate side effect of how the web operates, a way to compensate for the statelessness of the web.
Now back to Flex. Flex applications (or more rightly, Flash applications) are usually served by web servers and run inside of web browsers. But Flex applications are functionally a lot more like client-server applications than they are web applications. Like desktop client-server applications, Flex applications are loaded and the remain running as long as the app is in use. Like desktop client-server applications, Flex applications connect to back-ends and request or interact with data as needed. Like desktop client-server applications, Flex applications do not suffer the limitations of running in a too-thin client. And like desktop client-server applications, variables defined once in the app can remain defined, and objects instantiated can remain so (until you kill them, or until the application terminates).
In other words, Flex apps are stateful, much like desktop applications and client-server applications. If you need to remember user preferences, just create a variable or object to store these in and keep it around for the duration of the application execution. If you need to track shopping cart contents, keep these locally within the Flex app until checkout time when they’ll be submitted to the server. And so on.
(As a side note, if you need to maintain values across application usage, then you can even store values locally in local shared objects – the Flash Player’s equivalent to browser cookies).
So, the answer to the question “how do I maintain session state in a Flex application?” is “as a rule, don’t!”.

37 responses to “Flex And Session State Management”

  1. Joe Rinehart Avatar
    Joe Rinehart

    It’s funny how quickly we forget the simple things, isn’t it? When I first wrote a Flex app, I had a moment of "Ok, this is my user instance, how do I keep it arou….oh…yeah. I don’t have to worry about that."
    I have found it handy, though, to have a class (called something like, well, "Session," because that’s what my Web brain is used to) with static methods that do generic get/put. It lets me control things stored in session, like the example of user preferences, and control if/when to send them back to the server for something like persistence to a database. It also makes it a bit cleaner to access things in the "Session" (what an awkward term in this context!) from various places in the application.
    When the user returns, I can then recall their "Session" from the server, and restore the app (from high-level preferences down to the point of displayed views) exactly as it was when they last logged off.
    "Session" is probably a lousy name for it….maybe "Client" :)?

  2. Ben Forta Avatar
    Ben Forta

    Joe, funny, I did the same way back when, but it felt wrong, and so backpedaled quickly. 😉
    — Ben

  3. Adam Reynolds Avatar
    Adam Reynolds

    I have a real problem with this idea. Client/Server is fine within an intranet, you start farming this out to Internets, get somebody who knows what they are doing to analyse the comms between your local Flex client and the server backend, and you are going to get hit very hard.
    I have no issue with the flex client holding the user login information and then using this should the session expire, to re-aquire a session before performing actions on the server.
    Ben, you may disagree, but what you are proposing can result in security holes. It is important to stress that any app needs to protect certain functions and that relying on the fact the Flex app has validated a user 2 hours ago and wouldn’t be making this call unless they were logged in, just isn’t good enough.
    Even within a client/server environment, the client must be a valid client for that server. However as sessions expire, some automatic handshaking between the client and server to re-authenticate the user isn’t difficult to build into a flex app.
    Again this is about protecting certain functions within your app that you expose to the Flex client. In the same way that you force a user to login to a site to perform certain functions.

  4. Stacy Young Avatar
    Stacy Young

    Hi Adam,
    I don’t believe it’s really a change in security considerations when comparing flex and web apps. In both instances we’re talking about a client interacting with a server-side component. Difference with flex is that’s typically scaled down to atomic service calls or messaging. These in turn being locked down via J2EE security or what not…
    As for maintaining state, sorry if I’m misconstruing your point, but I wouldn’t hold login information on the client once authenticated. When a session has lapsed on the server and the next remote call fails …that should trigger the flex app to return to a login screen.
    -Stace

  5. Dreamer Avatar
    Dreamer

    oh,good article. in fact, when I creat a web app I always consider the "Session"..

  6. Nathanael Waite Avatar
    Nathanael Waite

    This thread is a interesting one. Having had to worry about session state so much in the past years of web development I do find it hard like Joe and Ben to give up my session ways of thinking.
    However I think as long as we have Flex and web apps that live together and work together we need to have some way for them to stay in sync. For example lets say you had a long application process that you put on the html form the use maintains the "LOGIN" session state every time they go from screen to screen or interaction with the server. In a flex app that all goes away because the user can go through the whole process without contacting the server and only try to make a request at the end.
    You have two choices from what I see. 1) give the flex app the abilty to log back in with data it used earlier or set your session timeout on the server for a longer period of time. If you keep having the application pop up a login screen all the time in your flex app it could be annoying.
    So with all that here is my point.. Sessions will still be there as long as we are accessing and using web content. However as Ben pointed out thier ussage will change we won’t need to store the cart on them the whole time. But they will be there to persist our authentication.
    Ok now its time for someone to blow holes in everything I just said and tell me the right solution 🙂 I would enjoy hearing other thoughts on this subject.

  7. Adam Reynolds Avatar
    Adam Reynolds

    Hi Stace,
    Holding login information inside a cookie (text file on machine) and inside a Flex app (inside an instance of a flash app) are very different things. In theory you can perform a huge amount of work inside a flex app before submitting it to the server. As the flex app is the one the user is primarily interacting with, it is important that the flex app appears to maintain the session.
    The flex client can hold the login information and re-submit it if it can determine if the server session still exists.
    To be honest if I was working on a Flex app for a couple of hours then submitted my work to be saved on the server and was asked to retype in my username and login, even though I had logged in hours ago, I’d be very unhappy.
    The important thing is that the user session is seemless between the server and client and a mechanism is provided to validate the flex client with the server.
    Like Ben said, holding session state on the server is not realistic with a Flex app (in fact it creates network overhead, pinging the server once every 10-20 minutes to tell the server the session is still valid).
    Should you want to time out the client, you can easily put in a screen lockout should the client be left unattended for too long. Remember it is all about user experience. Forcing a login because your flex client can’t revalidate itself is just painful.
    What happens when they type it in wrong, how do you hold the action the person was supposed to be performing, so after login they can resubmit the action?

  8. Ken Wilson Avatar
    Ken Wilson

    Interesting discussion and one that needs to be addressed thoroughly if Flex is to penetrate as deeply as it appears to deserve. I’m one of those on the edge of diving into Flex and right at the top of my list is figuring out security/authentication related issues since everything we do is heavily secured.
    One thing to keep in mind with respect to "screen lockouts" is that you may have no control at all over the OS at the client end. Any "lockouts" might very well need to be handled at the application level, perhaps some type of application lockout screen that requires logging back into the local app which then seemlessly handles the server validation without losing all their work.
    Being so early in the Flex learning curve, I’ve no idea if this is feasible. Just wanted to point out that assuming any degree of control over the client environment apart from Flash version might be expecting too much.

  9. Wayne Gibson Avatar
    Wayne Gibson

    I agree with Ken,
    I have consistantly tried to improve the nature in which the security process is been handled and this process does leave me alittle dewildered.
    I have tried to handle as much of the DB work in store procedures with lockouts etc. The main issue I have now is too find the best way to handle this in Flex. I have had to increase the session timeout value for my apps.
    Surely this is not secure?

  10. Ben Forta Avatar
    Ben Forta

    The comments here remind me of another discussion, form field validation. When creating form fields in HTML pages you need to be sure to validate form entries. You have a choice, you can do it client-side or server-side, and there are pros and cons to each. Client-side creates a far better user experience, server-side gives you the security and data protection that you need. It’s not either or, you need both.
    The same is true of managing session state in Flex apps. While the vary nature and user interaction of Flex apps makes them better suited for storing session data on the client, there is still a need to do validation and checking on the server. Obviously, if a user has to time out after a specific interval that *must* occur server-side too. But at the same time, remember who a logged in user is belongs on the client-side.
    It’s not either or, you need both. Flex apps are stateful, and so session data belongs on the client. But at the same time, to ensure security and the integrity of your application you will likely also need to do some checking on the server.
    — Ben

  11. Ben Forta Avatar
    Ben Forta

    One more point worth noting. If you need to proactively let a client know that a server-side event has occurred (maybe to let a user know that a database connection has timed out, or to force the client app to go to a login page after a set interval, etc.) that can be accomplished with Flex Data Services. Using FDS you really do have an open end-to-end connection, just like client-server apps, and server events can then force client side action to occur.
    — Ben

  12. Rick Root Avatar
    Rick Root

    Ben,
    What about hybrid applications? Flex apps seem to have access to session variables in remoting calls, but they aren’t the same session variables that are available in a regular cfm call it seems.
    This would seem to imply that I need to store my "shared data" between the CFM parts of my app and the flex app in a database instead of a memory variable, and that makes me sad!
    Rick

  13. Sergey Neskhodovskiy Avatar
    Sergey Neskhodovskiy

    Hello all,
    I will attempt to simplify the process by imitating a client-server dialog.
    1) If several calls are made to the server, the server must know whether they come from the same user or not, to be able to serve user-specific content. Imagine a dialog between a SERVER and a CLIENT (FLEX APP):
    CLIENT: Hello! I’d like to log in, username:hello,password:world.
    SERVER: Hello, you are authenticated as John Smith.
    CLIENT: Are there any new messages for me?
    SERVER: Pardon. Who are you?
    The server has to respond like that, because at the call 2, the flex app didn’t supply any user identifiable information ID at the second call! The server simply doesn’t know which user requests his/her messages!
    That is why, some data must persist both with client and server between the calls:
    CLIENT: Hello! I’d like to log in, username:hello,password:world.
    SERVER: Hello, you are authenticated as John Smith, your user id is 24.
    CLIENT: My user ID is 24. Are there any new messages for me?
    SERVER: Welcome John Smith! Here are your messages.
    Way better, but – see a security threat? A hacker could easily pretend to be a legitimate user just by omitting the first request and starting from the second, and supplying a random user ID. That is why, the ID generated by the server must be like a session identifier (e.g. an MD5 hash) rather that user ID: it must be generated on the fly by the server and stored on the server side in the SESSION variable as long as the session is valid.
    CLIENT: Hello! I’d like to log in, username:hello,password:world.
    SERVER: Hello, you are authenticated as John Smith, your session id is 34o8hng458g340b5983b. Your session expires in 2 hours. (Saves session ID and sets the expiration time for this session ID).
    CLIENT: My session ID is 34o8hng458g340b5983b. Are there any new messages for me?
    SERVER: Welcome John Smith! Here are your messages.
    This is way more secure, because the hacker doesn’t know which session IDs are actual on the server at the moment. Actually, it is more like the traditional session mechnism.
    Now we just have to find the best way for the Flex App to store and send session ID at each new request. Now the approach to this problem is up to you.
    What concerns me, I feel like writing a request wrapper function that appends a parameter to each URL sent with the send() method of the HTTPService object, and then I would call this function instead of "send()", and in its turn, this function would append session ID in the URL and call send(). But I am sure there are plenty of alternatives!

  14. Vincent Paoletti Avatar
    Vincent Paoletti

    I have a rather simple question on this issue. What if I have a flex application inside of a bigger web app.
    For instance let’s imagine I have a web mail in HTML/Coldfusion and I want to upload attachments.
    For this attachment upload I want to use flex (better user experience for multiple attachments uploading) When The flex app upload the attachment to the server, the server will present a login screen because the sessionid presented by the flash player is different from the one presented by the browser how do I cope with that ?
    Can I access the browser cookies from flex ?

  15. KevWong Avatar
    KevWong

    Bugger. So there wasn’t a solution. What was the point in writing the article? Now we know why there aren’t any banking or financial applications written in Flex. If everything has to be exposed to any idiot with a browser , that’s a huge problem. The security guys won’t even let us deploy your applications if ever user context and session variable is persisted in the freakin’ browser!!!

  16. Ben Forta Avatar
    Ben Forta

    KevWong, huh? User context and client content being on the client, that’s where it belongs – just as it does with a client-server app, or anything BUT a web app. Server-side session state management is a hack, it only exists because browsers are stateless – and so we have to work around it. It’s not a security feature, it’s a problem that has to be dealt with. Oh, and actually, some of the earliest adopters of Flex are financial and banking apps.
    — Ben

  17. al Avatar
    al

    Hi Adam,
    I don’t believe it’s really a change in security considerations when comparing flex and web apps. In both instances we’re talking about a client interacting with a server-side component. Difference with flex is that’s typically scaled down to atomic service calls or messaging. These in turn being locked down via J2EE security or what not…

  18. Brian Avatar
    Brian

    The reason banking people aren’t using it is because they are typically conservative about deploying cutting edge technology for fear user’s will reject it.
    Ben – Why doesn’t flex manage a session id so on the server side we can validate that the request is coming from someone we know of?

  19. Jeff Bouley Avatar
    Jeff Bouley

    Hi Jim, at the end of the article Ben mentioned using Flex’s shared objects to store session related data. I have used these quite often when needing to do so. So if you place your memberId there after a successful login (your login function should return a memberId to flex for this) you will be able to reference it very easily when needed. If you are using Cairngorm you could store it in the model which ultimately stores this reference in memory. For information on shared objects you can find it on live docs here: http://livedocs.adobe.com/flex/2/langref/flash/net/SharedObject.html. As for not having to pass vars back and forth for this effort I understand your concerns, but for session this should not apply (especially for portability reasons). I am fine with application and server variables though as they reflect the entire application and/or server side application and not the user. Good Luck!

  20. jimC Avatar
    jimC

    Hey Ben, it’s about a year after you wrote this blog and in that time this page has become the number one result for ‘flex session variables’ in google. I can’t believe I just wasted my time reading it. Don’t get me wrong, I learned coldfusion about 8 years ago from reading your books and I still buy both versions every release. You are THE guru. But what is up with not answering the question? Surely you can think of a hybrid situation where you would need to use a session variable in Flex. KevWong was pretty rude, but he was probably pretty frustrated because, like myself, he’s stuck trying to find an answer and not getting anywhere. And worse yet, if you google this term, most of the other results point back to this page.
    So anyway, I don’t want to drag on too long, I just want to point out that I use coldFusion because of the usually outstanding documentation and community support. If I want to use a session variable in Flex (even if it is wrong) I can. If I want to have someone tell me that I need to change everything I’m doing when I ask for help, I’ll go back to the php boards…
    By the way, let me actually state my problem which i have been trying to solve for a day or so now. I built a flex app so users can easily manage part of their profile on ou site. The user logs in, then goes to a section of profile management, and can open this flex app. He then enters some stuff and moves some levers, and then i call back to my cf app to enter that data into the DB.
    So obviously at the time i call the flex app, I need to pass in the memberId (but i should just have to reference it!). Then I need to call my processing cfc using remote services. Now, it was my understanding that when I call remote Services, i shouldn’t have to pass through the memberId because I am logged in and the cfc should be able to still use the session vars. So I think this is why some people have security concerns. I should never have to pass the memberId because it is in a session var. I think I see how to get the sessionVar in flex, but for the life of me, i can’t find out how to get it in the cfapp being referenced by Flex (which called it in the first place).
    So that’s it. I’d love to never use a session var, but i have to unless there is something I missed in you blog here. I’m sure thousands of frustrated developers hit this page and leave frustrated. You’re the number one result and a guy most of us learn from. Don’t leave us hanging!
    (sorry for the long post, back to google to try and find a solution…)

  21. Max Volos Avatar
    Max Volos

    Hello all
    to jimC when u invoking cfc components via remote object it is already in currents browser session (remember u could cover each function defenition with roles attribute?)
    IMHO good old session data should be on db or client where possible

  22. Randy Martin Avatar
    Randy Martin

    Wasn’t there a RemoteObject servlet defined in web.xml in Flex 1.0 that allowed you to access session variables? Whatever happened to that?

  23. Ben Forta Avatar
    Ben Forta

    Ok, I accept the criticism from Jim and others. I have posted a follow-up entry at http://www.forta.com/blog/index.cfm/2007/11/15/Flex-And-ColdFusion-Session-Variables.
    — Ben

  24. Arald Jean-Charles Avatar
    Arald Jean-Charles

    what about security? how does the server know it is always talking to the same client ?

  25. Ben Forta Avatar
    Ben Forta

    Same as any web page, if the client identifier matches it assumes it has the right client.
    — Ben

  26. Chandra Avatar
    Chandra

    Can anyone throw some light on Logon implementation with Flex and J2EE remote objects?
    Below is the application details:
    – Flex as User Interface to a document management web application
    – User has to be authenticated before access to any of the documents in the ECM software
    – I have Java code to authenticate once I receive user name and password from the client
    – I am planning to use remote object implementation.
    Questions:
    – How do I keep track of Log-on on each flex screen
    – How do I keep the same at the server side?
    – Do I have to make use of Session object in Flex?
    I did lot of googling, but I dint find correct answers. I hope this blog is correct to ask this.
    I would appreciate your responses and value your time
    Thanks,
    Chandra

  27. Chandra Avatar
    Chandra

    Hello Guys,
    I found out a solution to this problem and was able to implement the same requirement in Flex using remote object also.
    If you are looking for any help, you can email me!!!!
    Thanks,
    Chandra

  28. Mark Avatar
    Mark

    Chandra, What is your e-mail address? Or – could you post the work you did here? Thanks!

  29. Senthil Babu Avatar
    Senthil Babu

    A nice blog. Let me put my doubt very simple.
    I want to go through these steps
    1. Authenticate the user with his login information
    2. Then I can authorize him for any kind of actions.
    For eg:- reading from a database, writing data…
    Here Authentication is done only once. If I do it in flex, I have store his username in some var at client side and whenever i want to get data from server i have to pass this username. Ok, how can this be free from security hacks having the username on client side. Any one can post the username and get the data. It seem weird. But in HttpSession this is done differently, we got a session id which is less prone to hack and moreover hard to reproduce.

  30. Senthil Babu Avatar
    Senthil Babu

    Ok. I want to do NTLM Authentication. I have a server side filter fot that.
    How can I do that in flex.
    But how can i pass the user details to flex application.

  31. lee Avatar
    lee

    I was searching for discussions re flex and server side authentication and found this blog.
    It’s indicative that the reason there’s no mantra for this is purely because this is really the first ventures into ‘thick client’ web based transactional apps (ignoring javascript).
    The answer surely is as others said earlier, always protect the server side, if the session’s timed out then instruct the client to authenticate.
    You can keep persistent data stored on the client to redisplay the page and restore state once authenticated.
    Or the other cludge option I see is send a get request every interval to keep the server side session alive.
    Or am I missing something?

  32. lee Avatar
    lee

    I was searching for discussions re flex and server side authentication and found this blog.
    It’s indicative that the reason there’s no mantra for this is purely because this is really the first ventures into ‘thick client’ web based transactional apps (ignoring javascript).
    The answer surely is as others said earlier, always protect the server side, if the session’s timed out then instruct the client to authenticate.
    You can keep persistent data stored on the client to redisplay the page and restore state once authenticated.
    Or the other cludge option I see is send a get request every interval to keep the server side session alive.
    Or am I missing something?

  33. mitch Avatar
    mitch

    Without a server side session, how does a server know if a client is timed out and instruct it to re-authenticate? The server doesn’t even know what client a remoting request comes from without keeping track of sessions. Simply put, if there is no sessions, there is no session time outs.
    Also, Flex data services are implemented as servlets. It means a remote server call is still over HTTP, albeit in binary form. To the server exposing a service, there is no difference if the client is a flex app or a web app. While a flex app is a rich client, you can’t do away server side sessions. It’s simply an illusion.

  34. Rudhir Avatar
    Rudhir

    Hi All,
    This is one of the best blogs on Flex I have ever come accross.
    I would like to get a solution to my problem.
    I have a SiteMinder Server which authenticates the user and sets the userid in the browser cookies.
    Now, how do I retrieve the values stored in these cookie objects on Flex Side?
    Kindly reply asap.
    Regards,
    Rudhir

  35. Ameer Tamboli Avatar
    Ameer Tamboli

    Hi All,
    One of the simple solutions to carry the session from your ASP/JSP to Flex Application is – while rendering the html of the page in which Flex Application (SWF) pass the session id as parameter to swf. Store that session id in Flex’s Shared Objects and pass it with every request to server.

  36. Ameer Tamboli Avatar
    Ameer Tamboli

    Hi All,
    One of the simple solutions to carry the session from your ASP/JSP to Flex Application is – while rendering the html of the page in which Flex Application (SWF) pass the session id as parameter to swf. Store that session id in Flex’s Shared Objects and pass it with every request to server.

  37. Chengbo Yan Avatar
    Chengbo Yan

    Well, this article really helps me out.
    I shall never consider flex as normal web pages.

Leave a Reply