IdentityServer4 cookie expiration

2019-07-12 19:46发布

I have been reading the IdentityServer4 issue threads for about a day now, but am still really confused regarding the session/signin cookie expiration.

If I set the cookie expiration from the client like this (I'm using an IdentityServer3 client with IdentityServer4 server in order to enable ASP.NET 4.x webapps to authenticate):

app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                ExpireTimeSpan = new TimeSpan(10, 0, 0),
                SlidingExpiration = true
            });

I can open Chrome developer tools (F12) and look at the cookies and see that they are set to expire as soon as the browser closes (the expiration date on all cookies for IdentityServer are set to expire "1969-12-31T23:59:59.000Z", in other words, the client expiration didn't take).

That is the case regardless of whether I set both client and server authentication options UseTokenLifetime to true or not:

Client side:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                 ...
                 UseTokenLifetime = true,
                 ...

Server side:

services.AddAuthentication()
   .AddOpenIdConnect("MyLoginScheme", "A login scheme", options =>
          ...
          options.UseTokenLifetime = true;
          ...

I'm not sure how to get it to take the client cookie lifetime I've set.

1条回答
神经病院院长
2楼-- · 2019-07-12 20:38

Try this:

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            // …
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = async n =>
                {
                    // Set persistent cookie, 
                    n.AuthenticationTicket.Properties.IsPersistent = true; 
                    // and the expiration
                    n.AuthenticationTicket.Properties.ExpiresUtc = DateTime.Today.AddDays(1); 
                },
            },
            // …
        }

As for the IDS's cookie expiration, you can set it in the ConfigureServices of the Identity Server:

        services.Configure<IdentityOptions>(options =>
        {
            // …
            options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1);
            // …
        });
查看更多
登录 后发表回答