MVC Identity(2.0.1)中重新生成身份验证和验证间隔持续时间后,ExpireTimeSpan被忽略。

29

整天都在琢磨这个问题。我正在尝试在MVC Identity 2.0.1中设置“非常长”的登录会话(30天)。

我使用以下cookie启动:

      app.UseCookieAuthentication(new CookieAuthenticationOptions
        {

            SlidingExpiration = true,
            ExpireTimeSpan = System.TimeSpan.FromDays(30),
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/My/Login"),
            CookieName = "MyLoginCookie",
            Provider = new CookieAuthenticationProvider
            {                           
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),

                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

总的来说,它运作得很好。Cookie设置30天后有效,一切看起来都很好。

如果我关闭浏览器,等待“validateInterval”时间过去(这里是30分钟),我仍然登录,但Cookie现在只被重新发放为“session”(仍然是正确的Cookie名称)!30天的到期已经消失了。

如果我现在关闭/重新打开浏览器,我将无法再登录。

我测试了删除“Provider”,然后一切正常,几个小时后我仍然可以正常登录。

我读到最佳实践是使用印戳重新验证,所以不确定如何继续。


2.1.0 版本仍存在一个错误。 - QuantumHive
2个回答

37
SecurityStampValidator触发regenerateIdentity回调时,当前已认证的用户会重新使用非持久化登录重新登录。这是硬编码的,我不认为有任何直接控制它的方法。因此,登录会话仅在重新生成身份的时候运行到浏览器会话结束。

下面是一种方法,使登录持续,即使跨身份重建操作。该描述基于使用Visual Studio MVC ASP.NET Web项目模板。

首先,我们需要一种追踪持久化登录会话的方式,跨分离的HTTP请求。这可以通过向用户的标识添加“IsPersistent”声明来完成。以下扩展方法展示了一种实现方式。

public static class ClaimsIdentityExtensions
{
    private const string PersistentLoginClaimType = "PersistentLogin";

    public static bool GetIsPersistent(this System.Security.Claims.ClaimsIdentity identity)
    {
        return identity.Claims.FirstOrDefault(c => c.Type == PersistentLoginClaimType) != null;
    }

    public static void SetIsPersistent(this System.Security.Claims.ClaimsIdentity identity, bool isPersistent)
    {
        var claim = identity.Claims.FirstOrDefault(c => c.Type == PersistentLoginClaimType);
        if (isPersistent)
        {
            if (claim == null)
            {
                identity.AddClaim(new System.Security.Claims.Claim(PersistentLoginClaimType, Boolean.TrueString));
            }
        }
        else if (claim != null)
        {
            identity.RemoveClaim(claim);
        }
    }
}

接下来,当用户登录请求一个持久会话时,我们需要添加“IsPersistent”声明。例如,您的ApplicationUser类可能有一个GenerateUserIdentityAsync方法,可以更新为按以下方式接受一个isPersistent标志参数,以在需要时进行此类声明:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, bool isPersistent)
{
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    userIdentity.SetIsPersistent(isPersistent);
    return userIdentity;
}

现在调用ApplicationUser.GenerateUserIdentityAsync的任何人都需要传递isPersistent标志。例如,在AccountController.SignInAsync中对GenerateUserIdentityAsync的调用将更改为:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, 
    await user.GenerateUserIdentityAsync(UserManager));

to

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent },
    await user.GenerateUserIdentityAsync(UserManager, isPersistent));

最后,在Startup.ConfigureAuth方法中使用的CookieAuthenticationProvider.OnValidateIdentity委托需要一些关注,以在身份再生操作之间保留持久性细节。默认委托如下所示:
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
    validateInterval: TimeSpan.FromMinutes(20),
    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

这可以改为:
OnValidateIdentity = async (context) =>
{
    await SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(20),
        // Note that if identity is regenerated in the same HTTP request as a logoff attempt,
        // the logoff attempt will have no effect and the user will remain logged in.
        // See https://aspnetidentity.codeplex.com/workitem/1962
        regenerateIdentity: (manager, user) =>
            user.GenerateUserIdentityAsync(manager, context.Identity.GetIsPersistent())
    )(context);

    // If identity was regenerated by the stamp validator,
    // AuthenticationResponseGrant.Properties.IsPersistent will default to false, leading
    // to a non-persistent login session. If the validated identity made a claim of being
    // persistent, set the IsPersistent flag to true so the application cookie won't expire
    // at the end of the browser session.
    var newResponseGrant = context.OwinContext.Authentication.AuthenticationResponseGrant;
    if (newResponseGrant != null)
    {
        newResponseGrant.Properties.IsPersistent = context.Identity.GetIsPersistent();
    }
}

哇,谢谢你详细的回复!我会尝试一下 :) - GregTheDev
3
有人知道微软是否打算解决这个问题吗? - Matt Roberts
哇,我本来要问一个关于这个问题的问题,因为我和@GregTheDev有相同的症状。但是这对我起作用了。 - QuantumHive
@chrisg 非常感谢。 - Arun Prasad E S

4

3
你验证过了吗?我已经尝试过了,结果是一样的,问题没有解决。此外,在提供的页面上有一条评论,告诉我们这个问题还没有被解决。测试于Microsoft.AspNet.Identity.Core.2.2.1版本。 - AlexSolovyov
1
是的,我已经享受着这个修复程序一段时间了。 - robrich
你使用的 Identity.Core 版本是哪个? - AlexSolovyov
我发现仅仅更新 AspNet.Identity.Core 到 2.2.1 版本是不够的,但同时更新 AspNet.Identity.Owin 可以解决这个问题。 - Mr. Flibble
使用 AspNet.Identity.CoreAspNet.Identity.Owin 版本 2.2.1 无法解决此问题。 - Shahzad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接