Reputation: 1566
I am currently using Identity for a login system but the session token it creates offers a fixed expiry date of 10 hours. he spec for my system requires the session to expire if the user is idle for 20 minutes. I um unable to find anywhere in the source code to offer a rolling session state.
I have googled the issue and the only solution is to create a new session from the sessionAuthenticationModule every time the SessionAuthenticationModule_SessionSecurityTokenReceived event is raised in the global.asax.
if (validFrom.AddMinutes(halfSpan) < now && now < validTo)
{
var sam = sender as SessionAuthenticationModule;
e.SessionToken = sam.CreateSessionSecurityToken(
e.SessionToken.ClaimsPrincipal,
e.SessionToken.Context,
now,
now.AddMinutes(5),
e.SessionToken.IsPersistent);
e.ReissueCookie = true;
}
Is there a better alternative to this method?
Upvotes: 3
Views: 563
Reputation: 27104
Allen Brock, member of ThinkTecture, suggests we reissue the token if the session is still valid but more than halfway expired:
void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
SessionAuthenticationModule sam = FederatedAuthentication.SessionAuthenticationModule;
var token = e.SessionToken;
var duration = token.ValidTo.Subtract(token.ValidFrom);
if (duration <= TimeSpan.Zero) return;
var diff = token.ValidTo.Add(sam.FederationConfiguration.IdentityConfiguration.MaxClockSkew).Subtract(DateTime.UtcNow);
if (diff <= TimeSpan.Zero) return;
var halfWay = duration.TotalMinutes / 2;
var timeLeft = diff.TotalMinutes;
if (timeLeft <= halfWay)
{
e.ReissueCookie = true;
e.SessionToken =
new SessionSecurityToken(
token.ClaimsPrincipal,
token.Context,
DateTime.UtcNow,
DateTime.UtcNow.Add(duration))
{
IsPersistent = token.IsPersistent,
IsReferenceMode = token.IsReferenceMode
};
}
}
If you approve, you need not write it yourself but can call it from global.asax
:
public override void Init()
{
PassiveModuleConfiguration.EnableSlidingSessionExpirations();
}
See also Updating BootStrapContext with new SessionSecurityToken when using Sliding sessions in WIF with the SAM and Thinktecture IdentityModel for a problem with this: The BootStrapToken serialized to the current claims Identity remains the old one.
Upvotes: 1