37

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.

enter image description here

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

enter image description here

Yahia
  • 805
  • 7
  • 25
Ivan.Yu
  • 564
  • 1
  • 4
  • 12

4 Answers4

57

If IsPersistent property of AuthenticationProperties is set to false, then the cookie expiration time is set to Session (with the long name "Session Cookie", which is deleted after the browser is closed).

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);
        }        
    }
}
zeroG
  • 320
  • 2
  • 12
tmg
  • 19,895
  • 5
  • 72
  • 76
  • Perfect, I use your code and achieve the above function, thank you. In addition, I put the Owin from the 2.1.0 version to upgrade to 3.0.1. – Ivan.Yu May 08 '16 at 05:30
  • 3
    Which version of ASP.NET Identity is this for? I'm using 2.2.2 on the default ASP.NET MVC 5 template and to login I have the following line `var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: false, shouldLockout: false);` and there's no `ExpiresUtc` or any other way to set that. – empz Aug 23 '18 at 19:04
  • also want to know how to achieve this in newer version of ASP.NET Identity .... – phxism Jul 03 '20 at 04:20
  • @phxism: see my answer below – Dejan Oct 14 '20 at 12:07
10

Use this...

public void ConfigureAuth(IAppBuilder app)
{
  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
      ExpireTimeSpan = TimeSpan.FromHours(1),
  });            
}
Nabeel Zafar
  • 191
  • 10
9

In order to achieve the feature you are describing in ASP.NET Core 3.1, I configure authentication in Startup in the following way:

        services.ConfigureApplicationCookie(o =>
        {
            ...
            o.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            o.SlidingExpiration = true;
            ...
            o.Events.OnSigningIn = ctx =>
            {
                if (ctx.Properties.IsPersistent)
                {
                    var issued = ctx.Properties.IssuedUtc ?? DateTimeOffset.UtcNow;
                    ctx.Properties.ExpiresUtc = issued.AddDays(14);
                }
                return Task.FromResult(0);
            };
        });

Using the OnSigningIn callback, I explicitly set the expiration date to now + 14 days if the "isPersistent" check-box is clicked.

Dejan
  • 9,150
  • 8
  • 69
  • 117
0

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

This adds roughly 10 years 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..

Garth
  • 3,237
  • 2
  • 18
  • 28
  • Some browsers may expire cookies earlier than expected if you set the expiration later than [2038](https://en.wikipedia.org/wiki/Year_2038_problem). – Brian Mar 04 '19 at 16:12