Change default ASP.NET Identity Two-factor remember Cookie Expire Time
Asked Answered
C

2

13

I have been using ASP.NET Identity 2.2.1. Following is the code in post method of VerifyCode action.

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);
}

When both model.RememberMe and model.RememberBrowser is true browser remembers Identity and two factor cookie for 2 weeks. This is the default implementation.

But i only need to remember TFA for 8 hours. How can i do that?

I have been searching for the solution since last 10 days but i haven't found the solution. Any help would be much appreciated.

Following is the code in my StartUp class. It just doesn't take effect.

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();
    }
}
Cutler answered 22/6, 2015 at 12:36 Comment(3)
can be configured inside the ApplicationUserManager in App_Start\IdentityConfig.csSegmentation
https://mcmap.net/q/704028/-asp-net-identity-with-2fa-remember-browser-cookie-not-retained-after-session/153923Segmentation
@jp2code I just made another test and i found following: Case I, Check Remember me during username and password validation. Don't check Remember browser during code verification Result: ExpireTimeSpan in Startup.Auth.cs takes effect Case II Check Remember me during username and password validation Check Remember me during code verification Result: ExpireTimeSpan in Startup.Auth.cs doesn't take effect. Both cookies gets a ExpireTime of 2 weeks.Cutler
M
3

I'm a little late to the party but I ran into the same issue as the OP but in my case I needed to push the 2FA cookie out to much more than 2 weeks. I'm using 2.2.1 and actually found that the code from the github post in Magnus's post worked for me. I'll include the actual code here for ease of reference. Note that I commented out the original app.UseTwoFactorRememberBrowserCookie from my Startup.Auth code. I hope this can save someone else the nasty headache it gave me.

//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);
Muskmelon answered 24/7, 2018 at 14:10 Comment(0)
H
1

This seems to be a bug looking at the following GitHub issue and other threads on SO handling this issue. https://github.com/aspnet/Identity/issues/309

Looks like its fixed in the current Identity beta version but that is probably not a solution for you. I would go for the suggested work around at the following SO question

Hayne answered 1/7, 2015 at 21:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.