Sliding sessions in SharePoint 2010

The scenario

In a SharePoint federated scenario, the user session has the same validity time as the SAML token.

If the user is inactive during a certain period of time, the session must expire.

Implementation in SharePoint

To achieve this behavior, SharePoint provides a configuration called LogonTokenCacheExpirationWindow.

The way it works is detailed in the chart below.

image

Global.asax

Re-issuing the token in every request to the server may have performance penalties so the code below is optimized to issue the session token after a certain period of time. Note that, by implementing this approach, the inactivity time after the user is signed out is half of the LogonTokenCacheExpirationWindow.

E.g.: If the LogonTokenCacheExpirationWindow is 40 minutes:

  • For the first 20 minutes the token is not reissued.
  • If the user interacts with the server during the last 20 minutes, a new session token is issued.
  • If the user is inactive during the last 20 minutes, he will be signed out.

The Global.asax of the SharePoint website has to be replaced/updated with the following code:

<%@ Application Language=”C#” Inherits=”Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication”%>
<%@ Import Namespace=”System” %>
<%@ Import Namespace=”Microsoft.IdentityModel.Web” %>
<%@ Import Namespace=”Microsoft.SharePoint.IdentityModel” %>
<script Language=”C#” RunAt=”server”>

public override void Init()
{
base.Init();

SessionAuthenticationModule sam = FederatedAuthentication.SessionAuthenticationModule;
sam.SessionSecurityTokenReceived += SessionAuthenticationModule_SessionSecurityTokenReceived;
}

private void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
double sessionLifetimeInMinutes = (e.SessionToken.ValidTo – e.SessionToken.ValidFrom).TotalMinutes;
TimeSpan logonTokenCacheExpirationWindow = TimeSpan.FromSeconds(1);
Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
{
logonTokenCacheExpirationWindow =
Microsoft.SharePoint.Administration.Claims.SPSecurityTokenServiceManager.Local.LogonTokenCacheExpirationWindow;
});

DateTime now = DateTime.UtcNow;
DateTime validTo = e.SessionToken.ValidTo – logonTokenCacheExpirationWindow;
DateTime validFrom = e.SessionToken.ValidFrom;

if ((now < validTo) && (now > validFrom.AddMinutes((validTo – validFrom).TotalMinutes / 2)))
{
SPSessionAuthenticationModule spsam = sender as SPSessionAuthenticationModule;
e.SessionToken = spsam.CreateSessionSecurityToken(e.SessionToken.ClaimsPrincipal, e.SessionToken.Context,
now, now.AddMinutes(sessionLifetimeInMinutes), e.SessionToken.IsPersistent);

e.ReissueCookie = true;
}
}

</script>

Updating the LogonTokenCacheExpirationWindow in SharePoint using PowerShell

To update the LogonTokenCacheExpirationWindow, the following PowerShell has be ran.

This example shows how to set the window time to 40 minutes:

$sts = Get-SPSecurityTokenServiceConfig

$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan -minutes 40)

$sts.Update()

iisreset



4 Comments

  • Vivek Shukla says:

    Hi ,
    I have done same steps as you mention in blog , thats why sharepoint session is working fine , but after did steps I got one error , that when session expire after that if we redirect any page ‘SharePoint unhandled exception comes’ i.e.:
    Exception of type ‘System.ArgumentException’ was thrown.
    Parameter name: encodedValue
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentException: Exception of type ‘System.ArgumentException’ was thrown.
    Parameter name: encodedValue

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    Stack Trace:

    [ArgumentException: Exception of type ‘System.ArgumentException’ was thrown.
    Parameter name: encodedValue]
    Microsoft.SharePoint.Administration.Claims.SPClaimEncodingManager.DecodeClaimFromFormsSuffix(String encodedValue) +25829270
    Microsoft.SharePoint.Administration.Claims.SPClaimProviderManager.GetProviderUserKey(String encodedSuffix) +73
    Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous) +27256361
    Microsoft.SharePoint.SPWeb.InitializeSPRequest() +223
    Microsoft.SharePoint.WebControls.SPControl.EnsureSPWebRequest(SPWeb web) +365
    Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) +520
    Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.GetContextWeb(HttpContext context) +27
    Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.PostResolveRequestCacheHandler(Object oSender, EventArgs ea) +918
    System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
    …………………………………………………………………………………..
    our objective is redirect to custom login page for FBA if session expires , but exception come , ….
    Please help me how to solve this issue …

    Regards,
    Vivek Shukla
    09213503284

  • Ketan says:

    Hey,
    One quick question have you tried this with Output Cache turned on, if not give it a shot and you will see that the User’s session doesnt really follow the Sliding Expiration pattern.

  • Thanh-Nu Leroy says:

    Hi Federico,
    Thank you for this article. I would like to ask you some questions related to this subject:
    1. If we want to keep the session alive indefinitely as long as the user is actively working with the pages,
    can we ignore the incoming SAML Token lifetime? Apparently, nothing prevents you from setting the the
    “ValidTo” value to whatever you want? Also, when I read this article “http://blogs.msdn.com/b/vbertocci/archive/2010/06/16/warning-sliding-sessions-are-closer-than-they-appear.aspx”, it seems that we can extend the incoming token lifetime within the SessionAuthenticationModule_SessionSecurityTokenReceived handling?

    2. If we can extend for ever the incoming SAML token lifetime, is it recommended to do so? Most of the paper I read about this subject always use the incoming SAML token lifetime as a threshold. The problem is that when the incoming SAML token lifetime is too short, no one can work 🙁

    Thanks for your advice.
    TN

  • Ozgur says:

    Hi Federico,
    This is a nice and simple way to make SharePoint’s sessions sliding. Is updating Global.asax in this way supported by Microsoft? And if so, can this solution be packaged as a .wsp file. I appreciate your comments.
    Many thanks.
    Ozgur

Leave a Reply