IdentityServer4 icon indicating copy to clipboard operation
IdentityServer4 copied to clipboard

Q: How to properly work with cookies and sessions

Open jhermsen opened this issue 9 years ago • 11 comments

Can someone explain how to properly setup sessions and cookies?

Using: Login site - IdentityServer4 - MVC EntityFramework Identity

Main site - MVC, Client grant type: HybridAndClientCredentials - In Startup: UseCookieAuthentication / UseOpenIdConnectAuthentication

What I currently have working: - Login on IdentityServer - Cookie lifetime 5 days - Go to site logs in, cookie lifetime session? - wait a while, refresh page redirects to login site and goes back to site works

Not working - wait a while refresh (javascript/ajax) grid, failes. Because ajax call gets redirected to login, but doesn't reinit session.

So how to either get site cookie/session to also stay for several days / sliding lifetime. Or how do I get the script/ajax call to properly refresh the session.

Tried setting following on client, but cookie stays for session in browser:

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                ExpireTimeSpan = TimeSpan.FromMinutes(60),
                AutomaticAuthenticate = true
            });

Thanks for any help in the right direction.

jhermsen avatar Jan 16 '17 09:01 jhermsen

I have the same problem with cookies only being saved for the session even though I specify the ExpireTimeSpan

jimbo74 avatar Jan 17 '17 17:01 jimbo74

There's an open issue for it: https://github.com/IdentityServer/IdentityServer4/issues/656. We'll get to it soon.

In short, if you use your own cookie middleware, then you need to tell IdentityServer about it by setting the AuthenticationScheme on the AuthenticationOptions.

https://github.com/IdentityServer/IdentityServer4/blob/dev/src/IdentityServer4/Configuration/DependencyInjection/Options/AuthenticationOptions.cs#L21

brockallen avatar Jan 18 '17 20:01 brockallen

Been experimenting a bit, but I'm still not getting to work properly. Is someone please able to make a working example keeping the session active on both page and ajax calls?

jhermsen avatar Feb 01 '17 15:02 jhermsen

This is not related to IS anymore. closing

leastprivilege avatar Feb 05 '17 14:02 leastprivilege

@brockallen when you say "In short, if you use your own cookie middleware, then you need to tell IdentityServer about it by setting the AuthenticationScheme on the AuthenticationOptions." Do you mean in the IdentityServer project, or the mvc project?

My current IdentityServer Startup has: services.AddIdentityServer() .AddSigningCredential(cert) .AddAspNetIdentity() .AddConfigurationStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly))) .AddOperationalStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly))); ;

should this be like this? app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "ISCookies", ExpireTimeSpan = new TimeSpan(1, 0, 0), SlidingExpiration = true }); services.AddIdentityServer(options => { options.Authentication.AuthenticationScheme = "ISCookies"; }) .AddSigningCredential(cert) .AddAspNetIdentity() .AddConfigurationStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly))) .AddOperationalStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly))); ;

My mvc has:

app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "BobCookies", ExpireTimeSpan = TimeSpan.FromMinutes(30), SlidingExpiration = true, AutomaticAuthenticate = true, CookieName = "Bob",

            Events = new CookieAuthenticationEvents()
            {
                OnValidatePrincipal = async cookiecontext =>
                {
                    if (cookiecontext.Properties.Items.ContainsKey(".Token.expires_at"))
                    {
                        var expire = DateTime.Parse(cookiecontext.Properties.Items[".Token.expires_at"]);
                        if (expire <= DateTime.Now.AddMinutes(-5) || DateTime.Now > expire)
                        {
                            var refreshToken = cookiecontext.Properties.Items[".Token.refresh_token"];
                            var tokenClient = new TokenClient(_authority + "connect/token",
                                _clientId,
                                _clientSecret);
                            var response = await tokenClient.RequestRefreshTokenAsync(refreshToken);
                            if (!response.IsError)
                            {
                                cookiecontext.Properties.Items[".Token.access_token"] = response.AccessToken;
                                cookiecontext.Properties.Items[".Token.refresh_token"] = response.RefreshToken;
                                cookiecontext.Properties.Items[".Token.expires_at"] = DateTime.Now.AddSeconds((int)response.ExpiresIn).ToString();
                                cookiecontext.Properties.Items["NextAccessTokenRefresh"]= DateTime.Now.AddMinutes(tokenRefreshMinutes).ToString();
                            }
                            cookiecontext.ShouldRenew = true;
                        }
                    }
                }
            }
        });

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "BobCookies",
            Authority = _authority,
            RequireHttpsMetadata = false,
            ClientId = _clientId,
            ClientSecret = _clientSecret,
            ResponseType = "code id_token",
            Scope = { "openid", "grantapi","offline_access", "userdetails" },
            UseTokenLifetime = false, //true or false = no difference
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,
            Events = new OpenIdConnectEvents()
            {
                OnTicketReceived = notification =>
                {
                     notification.Response.Cookies.Append("NextAccessTokenRefresh", DateTime.Now.AddMinutes(tokenRefreshMinutes).ToString());
                    return Task.FromResult(0);
                }
            },
            TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role
            }
        });

But you'll see from the screenshot below, my cookies named bob are still only session cookies and they are ignoring the fact i'm setting the expiry on them. I just can't see what I need to do to change this and it seems like @jhermsen has the same issue.

thanks for any help you can offer.. bobcookies

jimbo74 avatar Feb 17 '17 15:02 jimbo74

We have some new docs around the cookie middleware: https://identityserver4.readthedocs.io/en/release/topics/signin.html

brockallen avatar Feb 17 '17 19:02 brockallen

Is there someone who use IdentityServer4 and Asp Identity who has an example of how to set lifetime of a cookie. Tried for weeks without luck.

snerting avatar Jun 21 '19 06:06 snerting

No I never got it to work as I wanted

jimbo74 avatar Jun 21 '19 08:06 jimbo74

My understanding there a couple of places to mange this.

You can set token / cookie expiration.

var builder = services.AddIdentityServer(options => {
                options.Authentication.CookieSlidingExpiration = true;
                options.Authentication.CookieLifetime = TimeSpan.FromDays(1);
            });

But you can also configure Token Lifetime per client.

primalfear avatar Jun 21 '19 10:06 primalfear

I think I finaly got a working solution. One thing that tricked me, was that I also was using External login, and there was this line:

await _signInManager.SignInAsync(user, isPersistent: false);

This cause that it's always will be a session cookie, because isPersistent is set to false

So the solution to have a persistent cookie, instead of session cookie is: In Startup:

public void ConfigureServices(IServiceCollection services)
{
	services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

	//Setting cookies lifetime. 
	//This configen has only something to say if isPersient is set to true in ExternalLogin.cshtml.cs, as: await _signInManager.SignInAsync(user, isPersistent: true)
	//Or 'Remember me' is set, when using AspNet Identity login Login.cshtml.cs (await _signInManager.PasswordSignInAsync(Input.Username, Input.Password, Input.RememberLogin, lockoutOnFailure: true);)
        services.ConfigureApplicationCookie(options => {
                var COOKIE_TIMESPAN = 1800;
                options.Cookie.Expiration = TimeSpan.FromSeconds(COOKIE_TIMESPAN);
                options.ExpireTimeSpan = TimeSpan.FromSeconds(COOKIE_TIMESPAN);
                options.Cookie.IsEssential = true;
                options.SlidingExpiration = true;
            });

	services.AddIdentityServer()
            .AddAspNetIdentity<ApplicationUser>();

        //Add more config, who not have to do with identity......, exluded here....
}

As comment above, to don't always get a session cookie when us External login I must in ExternalLogin.cshtml.cs, set the isPersistent to true:

await _signInManager.SignInAsync(user, isPersistent: true)

Pleased to know if there is some other, more simpler solution to this :-)

snerting avatar Jun 21 '19 11:06 snerting

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 10:01 lock[bot]