1

我正在使用 ASP.NET 框架 CookieAuthenticationProvider 生成具有 AspNet.Identity.Core 版本 2.2.2 的身份。

当我从前端查看 cookie 时,它​​似乎是正确生成的(CookieName、CookieDomain 都符合预期)。

但是,我希望每 X 秒刷新一次 cookie。在 Microsoft 文档中,它声明我可以为此使用 CookieAuthenticationProvider 对象上的 OnValidateIdentity 属性,但是,regenerationIdentityCallback 似乎永远不会被触发。

值得一提的是,我们在 UserManager<TUser, TKey> 中使用 int 变量作为 TKey 而不是 GUID(据我所知,这是标准)

当前代码如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = "Identity.Application",
    CookieName = $".AspNet.SharedCookie-{environment}",
    CookieDomain = ".example.com",
    LoginPath = new PathString("/"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity =
        SecurityStampValidator
            .OnValidateIdentity<UserManager<User, int>, User, int>(
                validateInterval: TimeSpan.FromSeconds(30),
                regenerateIdentityCallback: async (manager, user) =>
                {
                    var identity = await manager.CreateIdentityAsync(user, "Identity.Application");
                    return identity;
                },

                getUserIdCallback: (user) => Int32.Parse(user.GetUserId()))
    },
    TicketDataFormat = new AspNetTicketDataFormat(
        new DataProtectorShim(
            DataProtectionProvider.Create(keyRingFolderInfo, (builder) => { builder.SetApplicationName($"{environment}-{applicationName}"); })
            .CreateProtector(
                "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                "Identity.Application",
                "v2"))),
    CookieManager = new ChunkingCookieManager()
});

为什么 ValidateInterval 不每 30 秒重新生成一次身份?我还应该如何让它按我想要的方式工作?

4

1 回答 1

1

由于您有一个 int 键,因此您已经实现了自定义 UserManager、UserStore、(...)

当您实现自己的逻辑时,您还必须实现此接口:

[IUserSecurityStampStore<TUser, in TKey>]

在您的自定义 UseStore 类中(有关此接口的更多信息)

在这里你可以看到SecurityStampValidator的默认实现。

           // Only validate if enough time has elapsed
            var validate = (issuedUtc == null);
            if (issuedUtc != null)
            {
                var timeElapsed = currentUtc.Subtract(issuedUtc.Value);
                validate = timeElapsed > validateInterval;
            }
            if (validate)
            { ..... await regenerateIdentityCallback.Invoke(manager, user).WithCurrentCulture()

如您所见,此类决定调用regenerateIdentityCallback方法。调试这个方法,你就会明白为什么 regenerateIdentityCallback 被调用了。

于 2021-01-27T18:21:30.873 回答