我目前正在使用 Identity 作为登录系统,但它创建的 session token 提供 10 小时的固定到期日期。如果用户空闲 20 分钟,我的系统规范要求 session 过期。我无法在源代码中的任何地方找到提供滚动 session 状态的地方。
我用谷歌搜索了这个问题,唯一的解决方案是每次在 global.asax 中引发 SessionAuthenticationModule_SessionSecurityTokenReceived 事件时,从 sessionAuthenticationModule 创建一个新 session 。
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;
}
除了这种方法还有更好的替代方法吗?
最佳答案
ThinkTecture 的成员 Allen Brock 建议,如果 session 仍然有效但过期超过一半,我们将重新发布 token :
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
};
}
}
如果你同意,你可以不用自己写,可以在global.asax
中调用:
public override void Init()
{
PassiveModuleConfiguration.EnableSlidingSessionExpirations();
}
另见 Updating BootStrapContext with new SessionSecurityToken when using Sliding sessions in WIF with the SAM and Thinktecture IdentityModel对于这个问题:序列化为当前声明身份的 BootStrapToken 仍然是旧的。
关于c# - Thinktecture Identity v2 滚动 session 安全 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27598743/