更改默认 ASP.NET 身份 两因素记住 Cookie 过期时间

Posted

技术标签:

【中文标题】更改默认 ASP.NET 身份 两因素记住 Cookie 过期时间【英文标题】:Change default ASP.NET Identity Two-factor remember Cookie Expire Time 【发布时间】:2015-09-07 22:02:06 【问题描述】:

我一直在使用 ASP.NET Identity 2.2.1。以下是 VerifyCode 动作的 post 方法中的代码。

var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);

switch (result)

    case SignInStatus.Success:
        return RedirectToAction("Dashboard","Index");
    case SignInStatus.LockedOut:
        return View("Lockout");
    case SignInStatus.Failure:
    default:
        ModelState.AddModelError("", "Invalid code.");
        return View(model);

当 model.RememberMe 和 model.RememberBrowser 都是 true 时,浏览器会记住 Identity 和两个因素 cookie 2 周。这是默认实现。

但我只需要记住 8 小时的 TFA。我怎样才能做到这一点?

自过去 10 天以来,我一直在寻找解决方案,但我没有找到解决方案。任何帮助将不胜感激。

以下是我的 StartUp 类中的代码。它只是没有生效。

public partial class Startup

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

        string domainName = string.IsNullOrEmpty(Config.DomainName) ? "" : Config.DomainName;
        string cookieName = "AspNet." + domainName;

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            SlidingExpiration = true,
            ExpireTimeSpan = TimeSpan.FromHours(9),
            CookieDomain = domainName,
            CookieName = cookieName,
            Provider = new CookieAuthenticationProvider
            
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ProgenyUser, long>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                    getUserIdCallback: (id) => (id.GetUserId<long>()))
            
        );



        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        //app.UseGoogleAuthentication();
    

【问题讨论】:

可以在App_Start\IdentityConfig.cs的ApplicationUserManager里面配置 ***.com/q/28745143/153923 @jp2code 我刚刚进行了另一项测试,发现如下:案例 I,在用户名和密码验证期间检查记住我。验证码时不勾选记住浏览器 结果:Startup.Auth.cs 中的ExpireTimeSpan 生效 案例二 勾选用户名和密码验证时记住我 勾选验证码时记住我 结果:Startup.Auth.cs 中的ExpireTimeSpan 不生效.两个 cookie 的过期时间均为 2 周。 【参考方案1】:

我参加聚会有点晚了,但我遇到了与 OP 相同的问题,但在我的情况下,我需要将 2FA cookie 推迟到 2 周以上。我正在使用 2.2.1,实际上发现 Magnus 帖子中 github 帖子中的代码对我有用。为了便于参考,我将在此处包含实际代码。请注意,我从 Startup.Auth 代码中注释掉了原始 app.UseTwoFactorRememberBrowserCookie。我希望这可以避免其他人给我带来的令人讨厌的头痛。

//app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        CookieAuthenticationOptions cookieAuthenticationOptions = new CookieAuthenticationOptions();
        cookieAuthenticationOptions.AuthenticationType = DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie;
        cookieAuthenticationOptions.AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive;
        cookieAuthenticationOptions.CookieName = ".AspNet." + DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie;
        cookieAuthenticationOptions.ExpireTimeSpan = TimeSpan.FromDays(365);
        cookieAuthenticationOptions.SlidingExpiration = false;
        CookieAuthenticationExtensions.UseCookieAuthentication(app, cookieAuthenticationOptions);

【讨论】:

【参考方案2】:

这似乎是一个错误,查看以下 GitHub 问题和 SO 处理此问题的其他线程。 https://github.com/aspnet/Identity/issues/309

看起来它在当前的 Identity 测试版中已修复,但这可能不是您的解决方案。我会在以下解决建议的工作 SO question

【讨论】:

以上是关于更改默认 ASP.NET 身份 两因素记住 Cookie 过期时间的主要内容,如果未能解决你的问题,请参考以下文章

如何在 asp.net C# 中使用启用两因素身份验证的 office365 电子邮件帐户发送电子邮件?

重置密码且未配置两因素设备时如何获得两因素身份验证

更改 Angular 和 ASP.NET Core 项目中的默认身份路由

ASP.Net Identity 2 使用 SMS 密码登录 - 不使用双因素身份验证

Angular 和 Asp.Net Core - 启用 2 因素身份验证

使用部分身份框架在 ASP.NET Core 中存储用户 ID