How can keep the user logged in even after the browser has closed with Identity ASP.NET MVC framework?

回眸只為那壹抹淺笑 提交于 2019-12-11 07:05:58

问题


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.



来源:https://stackoverflow.com/questions/46588534/how-can-keep-the-user-logged-in-even-after-the-browser-has-closed-with-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!