IdentityServer4 icon indicating copy to clipboard operation
IdentityServer4 copied to clipboard

Changing the lifetime of the Identity Server cookie

Open naeemsarfraz opened this issue 9 years ago • 14 comments

The life of the Identity Server auth cookie is 10 hours, I want to change this. I've read the documentation around this but found things are a little different when you add AspNetIdentity into the mix.

The solution is to set the desired timeout period on the IdentityOptions object like so.

public void ConfigureServices(IServiceCollection services)
    ...

    services.AddIdentity<IdentityUser, IdentityRole>(options => {
        options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1);
    });

    ...
}

So it seems like I don't need to add my own Cookie middleware. Does that seem right? If so I'll submit a PR to make an addition to the documentation if you're ok with that.

P.S. Whilst trying to find a solution for this I tried to change the IdentityServerOptions.Authentication.AuthenticationScheme but found it had no effect because it was being set again in the AddAspNetIdentity<IdentityUser>() method. This method accepts a string to define the AuthenticationScheme as per the following example. Might also be useful to mention this in the docs too.

public void ConfigureServices(IServiceCollection services)
    ...

    services
        .AddIdentityServer(options => {
            options.Authentication.AuthenticationScheme = "myscheme"; //pointless
        })
        .AddAspNetIdentity<IdentityUser>("myscheme") //overwrites what was set above

    ...
}

naeemsarfraz avatar Mar 01 '17 14:03 naeemsarfraz

Yes, when you use our AddAspNetIdentity, we internally configure the AuthenticationScheme in IdentityServer to be the name of the default cookie from ASP.NET Identity.

brockallen avatar Mar 01 '17 18:03 brockallen

Thanks for the response.

In this example, using ASP.NET Identity Core, I see two cookies are dropped by Identity Server

  • .AspNetCore.Identity.Application
  • Identity.Application.Session

Are both required to persist auth, in a SSO scenario, for example? Just trying to understand why there are two cookies and not one.

naeemsarfraz avatar Mar 02 '17 09:03 naeemsarfraz

I have a similar issue with the authentication cookies. I thought this might be the right thread to post my question.

I have configured a cookie authentication scheme with sliding expiration time of one week, lets call it "main". I have configured the "main" cookie authenticatication scheme to be used by identity server in IdentityServerOptions.AuthenticationOptions.AuthenticationScheme. I am not using AspNetIdentity.

I also have a second authentitcation scheme needed for the temporary external authentication cookie since the app logs users in with external providers. Actually, the log-in is only with external providers, no local user, not sure if this matters. After I process the external cookie I sign out of the external scheme and sign in with the "main" authentication scheme and all seems to be working fine. I can see the "main" cookie in the browser with expiration time of one week from 'now'. The user remains logged in during the day. Client apps, have access to the API, etc. I also notice a second cookie in the browser called 'idsvr.session'.

The question is about the behavior of the identity server app itself, not the client app. The problem I am facing is that on the next morning the user is logged out in the identity server app, even though the "main" cookie is still present in the application store and it has not expired yet. The 'idsvr.session' cookie is missing though, not sure if this is important. Trying to figure out what might be that I am doing wrong. Why is there a second cookie and might it be related to the fact that the user gets logged out? My desired user experience is that the user remains logged in identity server, without having to log in again for quite a long time. Is the "main" cookie expiration time the only thing I have to get right because I don't think it is really taken into account right now.

Thanks a lot for anyone willing to give advice.

ydekova avatar Mar 16 '17 08:03 ydekova

Tried to update to the latest version (1.3.1 at the moment) and noticed that now there are two more options in AuthenticationOptions: CookieLifetime and CookieSlidingExpiration. I wonder, if I am not using a custom Authentication scheme but go with the built in one, will those settings be enough to configure long lived cookie? Also will the cookie be persistent between browser requests?

ydekova avatar Mar 16 '17 16:03 ydekova

We added those two settings because they are the most common reasons for using your own middleware. Persistence is not controlled by config, but rather imperatively in your code when you issue the cookie.

leastprivilege avatar Mar 17 '17 06:03 leastprivilege

Thanks, those options seem to work for me without the need of a custom auth. scheme. I've been testing for some days now and the cookie seems to be 'stable'.

To sum up with version 1.3.1 the easiest way to change the cookie lifetime it to configure CookieLifetime and CookieSlidingExpiration in AuthenticationOptions when registering the IdentityServer service, unless you are using AspNetIdentity in which case the AspNetIdentity scheme overrides the default IdentityServer scheme.

Not really related to IdentityServer but don't forget to set up your crypto-keys storage if you want to persist the cookies across server restarts and make sure all your server instances use the same folder (in case of load balancing)

services.AddDataProtection() .PersistKeysToFileSystem(mySafeFolder);

Also mind that persistent cookie is not the same as persistent tokens, so if you need that too, be sure to configure your token storage.

ydekova avatar Mar 21 '17 09:03 ydekova

Glad you got it working!

leastprivilege avatar Mar 21 '17 10:03 leastprivilege

I am using IdentityServer4 1.5.2. The only way to set custom expiration time was on SignIn

here is a snipped how was done

AuthenticationProperties props = new AuthenticationProperties   
{   
    IsPersistent = true,    
    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(sessionLifeTimeInMinutes)    
};
await this.HttpContext.Authentication.SignInAsync(user.Id.ToString(), user.Username, props);

lem0na avatar Aug 11 '17 09:08 lem0na

This code above was the ONLY thing that worked for me with .NET Core 2.0 + IdentityServer4

Startup.cs > ConfigureServices()

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(o =>
            {
                o.SlidingExpiration = false;
            });
            services.ConfigureApplicationCookie();

            services.AddAuthorization();

Startup.cs > Configure()

app.UseAuthentication();

AccountController.cs > Login()

                // Step 1: Find ApplicationUser using Email
                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "User account not found.");
                    return View(model);
                }

                // Step 2: Check if the Password given matches the ApplicationUser
                var validPassword = await _userManager.CheckPasswordAsync(user, model.Password);
                if (!validPassword)
                {
                    ModelState.AddModelError(string.Empty, "Password was invalid.");
                    return View(model);
                }
                
                // Step 3: Create the Application Cookie (8hr expiration)
                await _signInManager.SignInAsync(user, new AuthenticationProperties()
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow.AddHours(8)
                });

justintubbs avatar Mar 01 '18 03:03 justintubbs

Maaan, it would have been nice if this was implemented to allow you to configure the application cookie expiration:

var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
}

justintubbs avatar Mar 01 '18 03:03 justintubbs

@justin Not working for me

prisar avatar Oct 11 '18 20:10 prisar

Any updates with IdentityServer + AspNetIdentity on how to set cookielifetime?

NoelDMJ avatar Feb 25 '19 05:02 NoelDMJ

Any updates with IdentityServer + AspNetIdentity on how to set cookielifetime?

The same way it's always been -- change the lifetime of the ASP.NET Identity cookie. Check the ASP.NET Core docs.

brockallen avatar Feb 25 '19 09:02 brockallen

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Jan 11 '20 19:01 lock[bot]