How can keep the user logged in even after the bro

2019-08-03 02:59发布

问题:

Currently, each time the user browser closes, he/she will have to login again.

When they login, this is the code that I use to sign them in Identity.

SignInManager.SignIn(user, false, false);

Here is how my Authentication is configured today

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {        
        AuthenticationType = "SomeCustomName",
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(60),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        },
        SlidingExpiration = false,
        ExpireTimeSpan = TimeSpan.FromMinutes(60)
    });

    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(3));
    app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}

How can I keep the use logged in for 60 minutes even if he/she closed the browser?

回答1:

You should make 2 changes.

AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
SlidingExpiration = true,

You want to use a cookie so that it is persisted in the browser and can be re-read if the web site is opened again later. You also want to slide the expiration so that way each request will extend the lifetime of the cookie, otherwise the user will have to re-authenticate after 60 minutes from the first time the cookie is issued.

Supporting documentation:

  • CookieAuthenticationOptions Documentation
  • DefaultAuthenticationTypes

Finally the call to sign in should pass true for the 2nd parameter. The 3rd parameter is only relevant if you are using 2 factor authentication.

SignInManager.SignIn(user, true, false);

Side note

For security it is not a bad idea to also set option CookieHttpOnly = true which ensures that the cookie cannot be accessed by scripts/client side code.