c# - Thinktecture Identity v2 滚动 session 安全 token

标签 c# asp.net identity

我目前正在使用 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();
}

来源:http://brockallen.com/2013/02/17/sliding-sessions-in-wif-with-the-session-authentication-module-sam-and-thinktecture-identitymodel/

另见 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/

相关文章:

c# - 在 C# 中解析锯齿状数组

asp.net - 500万用户如何处理? ASP.NET 标识

mysql - 如何将此 MS SQL 脚本重写为 MySQL 脚本?

c# - 使用 javascript 中的参数调用 ASP.net 函数

linq - 无法对表执行创建、更新或删除操作,因为它没有主键

c# - 字典中的 string.Trim()

c# - 如何使用 C# 创建 JSON post 到 api

c# - 将 datetimepicker 的值传递给代码隐藏 (c#)

asp.net - 一个网站多个​​应用程序池

asp.net - 运行一次请求最好的地方在哪里?