How to set asp.net Identity cookies expires time

2019-03-08 19:49发布

问题:

I use Asp.Net Identity to control my app's authorization. Now, I need to do this: if the user does not operate in 30 minutes, jump to the login page, when he login does not select "isPersistent" checkbox. And, if he selected "isPersistent" checkbox, set the expiration date of cookie for 14 days. I try to do this by change the Startup.Auth.cs like this:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        SlidingExpiration = true,
        CookieName = WebHelpers.ConstStrings.AUTHCOOKIESNAME
    });
}

and the SignIn code like this:

private async Task SignInAsync(User user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    if (isPersistent)
    {
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }
    else
    {
        AuthenticationManager.SignIn(new AuthenticationProperties() { ExpiresUtc = new DateTimeOffset(DateTime.UtcNow.AddMinutes(30)) }, identity);
    }
}

But I found that when the user does not choose isPersistent checkbox, cookies's expiration date is already 'Session', not the current time plus 30 minutes.

The cookies status when use the code like after, so the 'remember me' checkbox can't work.:(.

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromMinutes(30),
            SlidingExpiration = true,
            CookieName = WebHelpers.ConstStrings.AUTHCOOKIESNAME
        });

回答1:

If IsPersistent property of AuthenticationProperties is set to false, then the cookie expiration time is set to Session.

If checkbox "remember me" is checked then AuthenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = true }, userIdentity); will create a cookie with expiration time equal to ExpireTimeSpan you set up in Startup.cs (defaults to 14days).

If checkbox "remember me" is NOT checked then you have to use AuthenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)}, userIdentity);. Again IsPersistent is set to true but now we give a value to ExpiresUtc so it does not use from CookieAuthenticationOptions from Startup.cs.

public override async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
{
    var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();
    // Clear any partial cookies from external or two factor partial sign ins
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
    if (rememberBrowser)
    {
        var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity);
    }
    else
    {
        //AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity);
        if (isPersistent)
        {
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, userIdentity);
        }
        else
        {
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }, userIdentity);
        }        
    }
}


回答2:

Use this...

public void ConfigureAuth(IAppBuilder app)
{
  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
      ExpireTimeSpan = TimeSpan.FromHours(1),
  });            
}


回答3:

I had the same issue and this code worked for me (inside the Startup.cs file)..

services.Configure<IdentityOptions>(options =>
{
    options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(9999);
});

This adds roughly 27 years (or never expire) to the persistent cookie.

NB: If you wanted less of an expiry time you could use TimeSpan.FromMinutes(1); for 1 minute or TimeSpan.FromSeconds(30); for 30 seconds etc..



回答4:

Based on the answer by @tmg, the following solution works perfectly by simply using in the [HttpPost]Login() action:

await SignInManager.PasswordSignInAsync(userName: model.Email, password: model.Password, isPersistent: !model.RememberMe, shouldLockout: true);

where isPersistent: !model.RememberMe (note the opposite !) gives, as one would expect,

expiration date = Session if the user chooses RememberMe = true

expiration date = ExpireTimeSpan (e.g. 15 min) if the user chooses RememberMe = false