Jun 21

Obtaining User Session state from a Visualforce page

When deploying non-native content such as Flash within a Visualforce page it is often necessary to pass user session information from the page into the content. This allows the embedded content to seamlessly use the session and not inconvenience the end user with an additional login prompt.

I first encountered this use case when starting development of DashConn using the Force.com Toolkit for Adobe AIR and Flex. This problem is supposed to have a very simple solution – access the User SessionId from the standard Visualforce global variable {!$Api.Session_ID} and pass this to the embedded content. At the time I soon encountered a bug where this SessionId did not correctly resolve to the user session. The result was that the login would fail within the Flash component.

As it turns out Visualforce pages maintain their own session id, different than the session id associated with Apex. The reason for this is that Visualforce pages have a different lifetime scope and communicate with different server URLs than Apex code. While both these unique session ids are intended to resolve to the same user session, this was not happening with the Visualforce SessionId.

The work-around for this issue was to instead use the session id obtained from Apex by implementing a simple custom Controller. This solution is documented here on the Force.com Discussion Boards.

I recently revisited this issue and happily discovered that the Visualforce global variable {!$Api.Session_ID} does now correctly resolve to the user session in Summer 2011. So the need for the custom controller appears to be gone.

One word of caution is that in following up with Salesforce.com support they could not find a specific fix put in at any time to address this bug. So hopefully this will continue to work correctly moving ahead!