【问题标题】:ASP.NET framework 4.8 cookie authentication provider does not trigger onValidateIdentityASP.NET 框架 4.8 cookie 身份验证提供程序不会触发 onValidateIdentity
【发布时间】:2021-04-23 20:41:12
【问题描述】:

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

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

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

值得一提的是,我们在 UserManager 中使用 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 秒重新生成一次身份?我还应该如何让它按我想要的方式工作?

【问题讨论】:

  • 我没有 PC 可以在这里测试,但你可以试试 [link]forums.asp.net/t/… 我的项目中有相同的代码,一年前编写的代码,我希望有相同的行为

标签: c# asp.net asp.net-mvc-4 .net-framework-4.8 cookie-authentication


【解决方案1】:

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

当你实现自己的逻辑时,你也必须实现这个接口:

[IUserSecurityStampStore<TUser, in TKey>]

在您的自定义 UseStore 类中(more infos about this interface)

这里可以看到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 被调用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2022-10-25
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多