Home > SharePoint 2010 > SharePoint 2010: Set session timeout and setup sliding sessions on an FBA enabled site

SharePoint 2010: Set session timeout and setup sliding sessions on an FBA enabled site


[Updated 12th of Sept 2012]

Please note that the below method is now redundant as long as you have SP 2010 April 2011 Cumulative Update installed. For more details please read this excellant blog post by Shawn Cicoria.

You can get the same to work now by running the PowerShell script below:

$sts = Get-SPSecurityTokenServiceConfig
$sts.FormsTokenLifetime = (New-TimeSpan -Minutes 60)
$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –Minutes 60)
$sts.Update()

This creates a sliding session effect whereby as soon as there is any activity before the expiry of the token it (the token) is renewed and it will usually only expire if there is 60 minutes of inactivity. If you do not have the SP 2010 April 2011 Cumulative Update installed then you can setup sliding session by following the original blog post below.

[Original Blog Post]

After struggling with this for a few days I finally figured out how to control this in SharePoint 2010.

In MOSS 2007 if you had a site that had windows authentication then you could specify the timeout by adding a timeout attribute in the sessionState element in your web.config. On the other hand if you had an FBA enabled site and wanted to control the session timeout you would do that by adding a timeout attribute in the forms element in the web.config.

The Problem

The problem is that in SharePoint 2010 the same thing does not work for a FBA enabled site. I spent a whole lot of time trying to search for a solution and ended up trying a lot of different things but nothing seemed to work. At one point I came across the powershell script below and thought I had finally found a solution:

$sts = Get-SPSecurityTokenServiceConfig
$sts.WindowsTokenLifetime = (New-TimeSpan -Minutes 60)
$sts.FormsTokenLifetime = (New-TimeSpan -Minutes 60)
$sts.Update()

However, soon I realised that this was causing the session to expire after 60 minutes regardless of the activity of the user. Eventually, I came across this very useful blog post.

The Solution

First of all we need to add some code behind to the Global.asax file of the SharePoint Web Application.

In your Visual Studio project add a new class file and call it Global.asax.cs (you can call it anything really) Then we need to add the following code to the Global.asax.cs file:

namespace MyNameSpace
{
    public class Global : SPHttpApplication
    {
        /// <summary>
        /// Executes custom initialization code after all event handler modules have been added.
        /// </summary>
        public override void Init()
        {
            FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += new EventHandler<SessionSecurityTokenReceivedEventArgs>(SessionAuthenticationModule_SessionSecurityTokenReceived);
            base.Init();
        }

        /// <summary>
        /// Handles the Start event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void Application_Start(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Handles the SessionSecurityTokenReceived event of the SessionAuthenticationModule control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Microsoft.IdentityModel.Web.SessionSecurityTokenReceivedEventArgs"/> instance containing the event data.</param>
        void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
        {
            // the timeout comes from the web.config
            int configuredTokenTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["SessionTokenTimeout"]);

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

            long timeLeft = e.SessionToken.ValidTo.Subtract(now).Ticks;
            TimeSpan tokenLifeTime = validTo.Subtract(validFrom);
            TimeSpan configuredTokenTimeSpan = new TimeSpan(0, configuredTokenTimeout, 0);
            // 37200000000 = 62 minutes
            if ((tokenLifeTime.Ticks > configuredTokenTimeSpan.Ticks) || (timeLeft * 2) < tokenLifeTime.Ticks)
            {
                SPSessionAuthenticationModule spsam = sender as SPSessionAuthenticationModule;
                e.SessionToken = spsam.CreateSessionSecurityToken(e.SessionToken.ClaimsPrincipal, e.SessionToken.Context,
                    now, now.AddMinutes(configuredTokenTimeout), true);
                e.ReissueCookie = true;
            }
        }
    }

Next we need to link this code behind to the Global.asax file.

Browse to the root of your Web Application Folder and open up the Global.asax file and add the following (modify the application tag with your specific assembly details):

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Language="C#" Inherits="MyNameSpace.Global,MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d4469032123b3e99a"%> 

Deploy your solution.

In the example above I am subscribing to the SessionSecurityTokenReceived event. In it I have some custom logic to implement a sliding session. Basically what I am doing is that I discard the original session token (which always seems to have a lifetime of 10 hours) and I create a new session token that has the lifetime I want. In my implementation I also added a key in the appsettings section of the web.config that controls the session timeout value:

  <appSettings>
    .......
    <add key="SessionTokenTimeout" value="60" />
    .........

Finally, I found that you need to run the following powershell script below as well to make the whole thing work:

$sts = Get-SPSecurityTokenServiceConfig
$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –seconds 1)
// set it to false for better client integration (thanks to Anirudh for pointing this out)
$sts.UseSessionCookies = $false
$sts.Update()
iisreset 

This is the only way I found that allowed me to control the Session Timeout in 2010. Please feel free to leave a comment if you have found a better and easier solution.

About these ads
  1. Andy Yun
    January 20, 2011 at 9:43 pm

    Hi Jalil,

    This is very good post and I have the same issue so far. Unfortunately I did make it work on my testing environment. It would be nice if you can give me step by step instruction. I am using SQL 2008 R2, Windows server 2008 R2 and SharePoint Server 2010 enterprise edition.

    Your reply is greatly appreciated.

    Thanks,

  2. jasear
    January 23, 2011 at 2:12 pm

    Hi Andy,

    Please check out my post again, I have made some changes to it. Hopefully it will help. Just follow “The Solution” section to try and implement it.

    In short this is what you need to do:

    1) Create a Class file (I called it Global.asax.cs as this was the code behind for the Applications Global.asax file) add the code I posted above in this file (make the changes that suits your specific requirement)
    2) Open up Global.asax file that is located in your Web Applications root folder on the file system. Add the tag that I posted above in the original post (make changes to the application tag to match your assembly, class and namespace details
    3) Open up your web.config and add a key in the appsettings section (see above again) that specifies the timeout value
    4) Run the powershell script posted in the end of the post above
    5) Do an IISReset (I dont think this is necessary but lets be on the safe side)

    Log in to your SharePoint site. Just to see if everything is working debug your code and put a break point on the SessionAuthenticationModule_SessionSecurityTokenReceived event. It should hit the breakpoint every time you access a page in your site. You can see if things are getting setup correctly in there.

  3. June 2, 2011 at 8:35 am

    nice solution but the following command will have impact on Client integration

    $sts.UseSessionCookies = $true

    • jasear
      December 27, 2011 at 12:38 am

      Yes you are correct and this is a very good point. This controls whether a persistent cookie is issued or not. If a persistent cookie is issued it works better with other client applications as they all share the same cookie.

  4. Nici
    October 4, 2011 at 9:42 pm

    Hi Jalil,

    I feel like I am really close in following your example but I not sure I have it implemented right. So if I want the session to timeout and prompt the user for a new certificiate after 10 minutes of inactivity — do I have to make other changes other than

    the webconfig

    and the script $sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –minutes 10)

    It seems to be automatically logging out my user and taking me to the sign in page instead of prompting for a new certificate/session. Do you know why it might do this?

    Thank you,
    Nici

  5. Gary Martin
    October 7, 2011 at 1:55 pm

    Does this implementation take into consideration how to handle links into other application? sdo if I authenticate into SharePoint and then go to another application how do you control the timeout control in SharePoint 2010? thx

    • jasear
      December 27, 2011 at 12:46 am

      If you follow this example then you will be using persistent cookie (which is saved as a file on the client machine) which gives better integration with other client applications as they all share the same cookie.

  6. Elad
    November 16, 2011 at 2:22 pm

    thanks for article.

    How u can implement “remember me” option? in this case user should have cookie with long term exipration date and “never” be logout until he click the “sign out” or delete it’s own cookies manually…

    • jasear
      December 27, 2011 at 12:59 am

      If you run the following powershell script:

      $sts = Get-SPSecurityTokenServiceConfig
      // set it to false for better client integration (thanks to Anirudh for pointing this out)
      $sts.UseSessionCookies = $false
      $sts.Update()

      You should then see the “remember me” checkbox on your login page (assuming it is the OTB SharePoint login page).

      As for the expiration date try this:

      $sts = Get-SPSecurityTokenServiceConfig
      $sts.ServiceTokenLifetime = (New-TimeSpan -Days 365)
      $sts.FormsTokenLifetime = (New-TimeSpan -Days 365)
      $sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –seconds 1)
      $sts.UseSessionCookies = $false
      $sts.Update()

  7. December 27, 2011 at 8:36 pm

    It’s always excellent whenever you go through a post which is not simply instructive but also entertaining. I have to book mark SharePoint 2010: Set session timeout and setup sliding sessions on an FBA enabled site Jalil Sear's [MCPD SharePoint 2010] Weblog inside my personal pc. I’ve been trying to find details about this topic for days and this is the greatest I have located. I liked this blog post.

  8. Alan Zhang
    January 12, 2012 at 2:09 am

    Hi Janil,

    Thanks for your information. It’s very useful. I actually convert your solution to a HttpModule and an web application level feature so it can be packaged and deployed through a wsp package. Changing global.asax method is difficult to maintain in a multi-server farm environment.

  9. vikram
    January 23, 2012 at 6:58 am

    I tried above code for time out session..but i got this error…
    The type ‘System.Web.HttpApplication’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a’. D:\Satish\SPTestProjects\Time-Out\Time-Out\Global.asax.cs
    please help me on this problem…

    • jasear
      January 24, 2012 at 10:36 am

      Hi Vikram,

      It seems as if you are missing a project reference. Please add System.Web assembly to your project references.

  10. Krishna Reddy
    January 24, 2012 at 7:34 pm

    Excellent post..,

    How to show an custom Session timeout page when an the user session timeout expired.
    In the custom page i will provide a link saying “Login here”.

    Once the user clicks on the Login Here it needs to take to the login page.

    Thanks,
    Hari

    • jasear
      January 24, 2012 at 11:41 pm

      Hi Krishna,

      If I understand it correctly, when the session expires you want the user to be redirected to a custom page of your choice where you will provide a link to the login page.

      I have not tried this, so cannot guarantee that it will work, but I would look at Session_End event in the global.asax. It should fire up when a user session ends and in here you can redirect the user to the custom page where you provide them with a login link.

      There are a few other more sophisticated solutions to this issue of yours but I would try the above first.

  11. Krishna Reddy
    January 27, 2012 at 7:40 am

    Hi jasear,

    I tried with the above event(session_event) of global.asax file. when the session expired the page is redirect to the login page…

    i log some information in the session_end event .., but it is not firing.

    can you please provide any other information which help me to resolve this issue.

  12. jasear
    January 27, 2012 at 12:35 pm

    Hi Krishna,

    It seems as if the Session_End event only fires if you are using InProc session state mode.

    In the example above I am subscribing to SessionAuthenticationModule.SessionSecurityTokenReceived event, the SessionAuthenticationModule class also has a couple of other events you can subscribe to namely SignOut and SigningOut. I am not completely sure how they work i.e. will they fire if a session times out due to inactivity. I would look into these events and see how they behave.

    Another option you have is to create a custom login page with code behind and in there see if you can work out if you have been redirected to it due to the expiration of a session if so then redirect them to your custom page. I am not exactly sure how you would work that out but it is worth exploring.

  13. Krishna Reddy
    January 28, 2012 at 6:15 am

    Hi jasear,

    Any updates on this?

    • jasear
      January 28, 2012 at 10:33 pm

      Hi Krishna,

      Please read my comment above.

  14. vj
    February 2, 2012 at 2:48 am

    What abt the usage of asp.net session in SP 2010 using State Service ? what is the difference ?

  15. VR
    March 7, 2012 at 12:13 am

    I followed same steps, but when I try to debug it, it doesn’t go to breakpoint as it is mentioned here. I am not sure how to test this concept. I ran the Sharepoint site and ketpt it for 60 minutes, nothing happend.

    “Log in to your SharePoint site. Just to see if everything is working debug your code and put a break point on the SessionAuthenticationModule_SessionSecurityTokenReceived event. It should hit the breakpoint every time you access a page in your site. You can see if things are getting setup correctly in there”

  16. jasear
    March 7, 2012 at 5:06 pm

    Hi VR,

    Did you modify the Global.asax file of your Web Application as mentioned in the blog post above?

    When you log in to the site and debug your code it should hit that event when you browse to any page on the site.

    • VR
      March 7, 2012 at 6:35 pm

      Thanks Jasear!

      I have changed the web.config in my inetpub\wwwroot…. Also, in my SharePoint application
      When I created Global.asax.cs, it used the web.config file which is added from inetpub\….. Also, I copied my assembly GAC
      a)Which web.config it will use b)Once I deploy how do I confirm deployemnet is correct

  17. VR
    March 7, 2012 at 6:36 pm

    Thanks Jasear!
    I have changed the web.config in my inetpub\wwwroot…. Also, in my SharePoint application
    When I created Global.asax.cs, it used the web.config file which is added from inetpub\….. Also, I copied my assembly GAC
    a)Which web.config it will use b)Once I deploy how do I confirm deployemnet is correct

  18. VR
    March 7, 2012 at 6:42 pm

    I need to resolve this ASAP.

    • VR
      March 8, 2012 at 2:06 am

      I think it is working, but with debug mode it didn’t work.
      With this functionality, if I want to pop-up a box to continue or not on client-side, how do i add functionality.

      • jasear
        March 13, 2012 at 8:06 pm

        I am not sure why it isnt working in debug mode for you. Are you sure you deployed your assembly in debug mode (and not release) and then attached the debugger to the worker process?

        As for the popup functionality, I am not sure what your exact requirements are but my feeling is you might need a custom login page to achieve that.

  19. VR
    March 14, 2012 at 2:57 pm

    Thanks!
    I have client side scripting, which pops up a message dialog box when session time out happens, but not able use your code to sync with it. How do I invoke or sync client side with your concept.

  20. March 16, 2012 at 9:27 am

    Hi Jalil,

    Above post was very interesting & it helped me a lot to fix my issue that I was facing from long time. I observed one thing session is not sliding if we don’t execute last step i.e. Power shell script for LogonTokenExpirationWindow. Session would slide only after running last step. Could you please put some light on LogonTokenExpirationWindow setting which is causing session to slide.

    Thanks in advance.

    Regards,
    Junaid

    • jasear
      March 16, 2012 at 9:54 am

      Hi Junaid,

      The session expires when:

      SessionToken.ValidTo – LogonTokenExpirationWindow < DateTime.UtcNow

      In the powershell script above I am setting it to such a low value (1 second) so that it becomes almost irrelevant in determining the session expiration duration.

      Please have a look at this excellant blog post by Federico Boerr: http://blogs.southworks.net/fboerr/2011/04/15/sliding-sessions-in-sharepoint-2010/ that explains in detail the purpose of the LogonTokenExpirationWindow.

      Regards,

      Jalil

  21. Hameed
    September 7, 2012 at 12:29 pm

    Hi,
    we are having Webapplication with FBA and custom login page. We are facing an issue that user is logged out of the application and redirected login page within a time span of 3 min and this happening always

    • jasear
      September 7, 2012 at 9:06 pm

      Hi Hameed,

      Can you please try running this powershell command on your server:

      $sts = Get-SPSecurityTokenServiceConfig
      $sts.FormsTokenLifetime = (New-TimeSpan -Minutes 60)
      $sts.Update()

      This should set the timeout to 60 minutes, you can adjust the time in the command to suit your requirements.

  22. Hameed
    September 10, 2012 at 8:27 am

    I have tried that command and set the timeout . we are still facing the issue

    • jasear
      September 10, 2012 at 8:45 am

      Can you run the following powershell:

      $sts = Get-SPSecurityTokenServiceConfig
      $sts.WindowsTokenLifetime
      $sts.FormsTokenLifetime
      $sts.LogonTokenCacheExpirationWindow
      $sts.UseSessionCookies

      And then please post the values you get.

      • Hameed
        September 10, 2012 at 8:58 am

        $sts = Get-SPSecurityTokenServiceConfig
        $sts.WindowsTokenLifetime

        Days : 0
        Hours : 0
        Minutes : 20
        Seconds : 0
        Milliseconds : 0
        Ticks : 12000000000
        TotalDays : 0.0138888888888889
        TotalHours : 0.333333333333333
        TotalMinutes : 20
        TotalSeconds : 1200
        TotalMilliseconds : 1200000

        $sts.FormsTokenLifetime

        Days : 0
        Hours : 0
        Minutes : 20
        Seconds : 0
        Milliseconds : 0
        Ticks : 12000000000
        TotalDays : 0.0138888888888889
        TotalHours : 0.333333333333333
        TotalMinutes : 20
        TotalSeconds : 1200
        TotalMilliseconds : 1200000

        $sts.LogonTokenCacheExpirationWindow

        Days : 0
        Hours : 0
        Minutes : 20
        Seconds : 0
        Milliseconds : 0
        Ticks : 12000000000
        TotalDays : 0.0138888888888889
        TotalHours : 0.333333333333333
        TotalMinutes : 20
        TotalSeconds : 1200
        TotalMilliseconds : 1200000

        $sts.UseSessionCookies
        False

    • jasear
      September 10, 2012 at 9:05 am

      Hameed,

      Run this:

      $sts = Get-SPSecurityTokenServiceConfig
      $sts.LogonTokenCacheExpirationWindow = (New-TimeSpan –seconds 1)
      $sts.Update()
      iisreset

      This should fix it. Your timeout is set to 20 minutes and the LogonTokenCacheExpiration is also set to 20 minutes which means your token will expire almost imediately after it is issued. Let me know if this works.

      • Hameed
        September 12, 2012 at 8:42 am

        Hi,
        i have tested with setting you have suggested. I am still facing the same issue.

  23. jasear
    September 12, 2012 at 12:12 pm

    Hameed :

    Hi,
    i have tested with setting you have suggested. I am still facing the same issue.

    Hameed,

    I am not sure why it is not working for you. The only thing I can think of is that the SAML Token lifetime is set to something like 3 minutes which basically renders all other settings irrelevant and you will end up getting logged out after 3 minutes (please read this for more details: http://blogs.southworks.net/fboerr/2011/04/15/sliding-sessions-in-sharepoint-2010/).

    However, saying that, I have never been able to figure out a way of changing the SAML Token lifetime so I am not sure how you would have done this. Am I correct in assuming you are using FBA with ASP.NET Membership as the provider and the users are stored in SQL?

    Can you also confirm if you are doing anything in the custom login page?

  24. May 16, 2013 at 8:15 am
  25. Andy
    August 14, 2013 at 1:21 pm

    EXCELLENT EXCELLENT information, I am a jr admin for my company and I configured and deployed this while my superior was vacation. She came back very impressed. surprisingly I got it to work for us on the first go around with minor changes to our needs of course. I still have it in our test site and I am anxiously awaiting approval to deploy in out next wsp.
    thanks so

    • Andy
      August 14, 2013 at 1:23 pm

      our next wsp… sorry couldnt leave the typo

  26. August 6, 2014 at 6:52 am

    Reblogged this on Ravi Ranjan Karn.

  1. May 14, 2012 at 6:05 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: