Archive for May, 2011

Enabling Sliding Expiration With Windows Identity Foundation & MVC

Wednesday, May 25th, 2011

It appears that out of the box Windows Identity Foundation only allows fixed length for sessions. So if your STS service is configured to expire after 15 minutes (the default is 60 minutes) then your security token will be invalid after 15 minutes from the first time you log on regardless of whether or not your session was active.

Currently the only way to implement sliding expiration is manually through code. I banged my head against this for a number of hours yesterday and did find a number of solutions out there none of them complete. In the end adding this code to the global.asax of the web site did the trick. It requires reissuing the security token at which point you can set when the token IsValidTo property of the token to whatever you require.


protected void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)


    var sessionToken = e.SessionToken;

    SymmetricSecurityKey symmetricSecurityKey = null;


    if (sessionToken.SecurityKeys != null)

        symmetricSecurityKey = sessionToken.SecurityKeys.OfType<SymmetricSecurityKey>().FirstOrDefault();


    Condition.Requires(symmetricSecurityKey, "symmetricSecurityKey").IsNotNull();


    if (sessionToken.ValidTo > DateTime.UtcNow)


        var slidingExpiration = sessionToken.ValidTo - sessionToken.ValidFrom;


        e.SessionToken = new SessionSecurityToken(








        e.ReissueCookie = true;




        var sessionAuthenticationModule = (SessionAuthenticationModule) sender;




        e.Cancel = true;