oidc-client-js icon indicating copy to clipboard operation
oidc-client-js copied to clipboard

Question How to handle default authentication timeout from the server

Open samtheprogrammer opened this issue 8 years ago • 10 comments

Hi , I have a question. How to handle session max authentication timeout from the oidc server. Meaning no new token wills be provided by the oidc server since max authentication time have been reached. I am just wondering which event should i use to prompt the user to re-login. Should i use token expired event or user Logged out event or silentRenewError event since silentRenew should fail when timeout happens on the server.

samtheprogrammer avatar Jun 28 '18 18:06 samtheprogrammer

How to handle session max authentication timeout from the oidc server

this is based on the cookie lifetime at your token server. once the user's session at the token server is ended, then on silent renew this library will get an error indicating that login is required.

brockallen avatar Jun 30 '18 15:06 brockallen

Thanks.

samtheprogrammer avatar Jul 11 '18 18:07 samtheprogrammer

@brockallen

this is based on the cookie lifetime at your token server. once the user's session at the token server is ended, then on silent renew this library will get an error indicating that login is required.

Can you please expand on this? I have what I think is a pretty standard IS4 implementation, with a single Angular client leveraging oidc-client-js. automaticSilentRenew is enabled, and is successful on the client... until it isn't. My users are being logged out (redirected to the IS4 logout page) when automaticSilentRenew suddenly fails. For troubleshooting, I have:

  • Enabled info logging within IS4.
  • Set the AccessTokenLifetime property for this Angular IS4.Client entry to 90 seconds.
  • Left the default value of 60 for the UserManagerSettings. accessTokenExpiringNotificationTime property, which I understand to mean that a new silent token renewal should fire about every 30 seconds (when combined with the above AccessTokenLifetime value).
  • Turned on logging within the client, so I could watch when the silent renewal was successful, as well as when it failed. I also checked the "Preserve log" within Chrome's dev tools. Here's what I saw:

On the client:

screen shot 2018-09-18 at 4 11 11 pm

On the server:

[Information] Showing error: prompt=none was requested but user is not authenticated

I believe the default ExpireTimeSpan for the AuthorizationTicket contained within the cookie is 14 days, but according to the above logs, I was auto-logged out right at about 30 minutes; I did nothing to explicitly log myself out of IS4.

Here is my Startup config:

var configConnectionString = AppSettings.ConnectionStrings.IdentityServerConfig;
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

services.AddIdentityServer()
    .LoadSigningCredential()
    .AddAspNetIdentity<ApplicationUser>()
    // this adds the config data from DB (clients, resources)
    .AddConfigurationStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(configConnectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    // this adds the operational data from DB (codes, tokens, consents)
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(configConnectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    });

// this project hosts API endpoints that are protected by this same IdentityServer instance
// http://docs.identityserver.io/en/release/topics/add_apis.html
services.AddAuthentication()
    .AddIdentityServerAuthentication(AuthSchemes.Token, options =>
    {
        options.ApiName = AppSettings.IdentityServer.ApiName;
        options.Authority = AppSettings.IdentityServer.Authority;
    });

And here is my UserManagerSettings for the oidc-client-js UserManager:

export const userManagerSettings: UserManagerSettings = {
  authority: `${environment.oidcAuthorityUri}`,
  client_id: 'my-app',
  redirect_uri: `${environment.oidcRedirectBaseUri}/auth/sign-in-callback`,
  post_logout_redirect_uri: `${environment.oidcRedirectBaseUri}/`,
  response_type: 'id_token token',
  scope: 'openid identity-server-4.api my-app.api email',
  filterProtocolClaims: true,
  loadUserInfo: false,
  automaticSilentRenew: true,
  silent_redirect_uri: `${environment.oidcRedirectBaseUri}/assets/oidc/silent-refresh.html`
  monitorSession: false // this will prevent the user from being auto-logged out from CollabApp whenever they're logged out from IdentityServer.
};

As far as the issuing of the auth cookie itself:

I'm using code from your QuickStart.UI.

jayoma avatar Sep 18 '18 21:09 jayoma

Set the AccessTokenLifetime property for this Angular IS4.Client entry to 90 seconds.

That seems very aggressive, IMO.

As for the rest of your question -- I don't really know. I think it would require some debugging. It sounds like for some reason your cookie is getting lost/expired after 30m. Perhaps something related to the ASP.NET Identity security stamp and its cookie renewal?

brockallen avatar Sep 19 '18 00:09 brockallen

Thanks for your quick reply. Determining that it was expiring at 30 minutes was the key to solving this (I'm 99% sure it's solved; gonna deploy to a staging server to verify). Once I used "30 minutes" in my search term, I stumbled into this stackoverflow post. I revised my Startup config as follows - again using very aggressive numbers so I don't have to sit and wait for the results while testing, and it appears to be successfully sliding my ticket's expiration date/time forward:

var configConnectionString = AppSettings.ConnectionStrings.IdentityServerConfig;
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

services.AddIdentityServer()
    .LoadSigningCredential()
    .AddAspNetIdentity<ApplicationUser>()
    // this adds the config data from DB (clients, resources)
    .AddConfigurationStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(configConnectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    // this adds the operational data from DB (codes, tokens, consents)
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(configConnectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    });

// this project hosts API endpoints that are protected by this same IdentityServer instance
// http://docs.identityserver.io/en/release/topics/add_apis.html
services.AddAuthentication()
    .AddIdentityServerAuthentication(AuthSchemes.Token, options =>
    {
        options.ApiName = AppSettings.IdentityServer.ApiName;
        options.Authority = AppSettings.IdentityServer.Authority;
    })
    .Services.ConfigureApplicationCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);
        options.SlidingExpiration = true;
    });

The last 5 lines are the key. Now that it seems to be working properly, I'll be backing all of those values off to reasonable time spans again.

jayoma avatar Sep 19 '18 00:09 jayoma

Wanted to circle back once more, and say that my last comment above was not the complete fix:

services.ConfigureApplicationCookie(options =>
{
    options.ExpireTimeSpan = TimeSpan.FromMinutes(AppSettings.Identity.AuthTicketExpiresInMinutes);
    options.SlidingExpiration = AppSettings.Identity.AuthTicketSlidingExpiration;
});

However, these config options in conjunction with the following seem to have resolved the issue AND allowed me to take full control over the AuthorizationTicket's expiration.

The real problem is that in order for ASP.NET Core Identity to perform its security stamp validator check, the AspNetUser.SecurityStamp value needs to exist in my User's claims. A standard IS4 + Identity setup does not include this claim in the auth cookie by default. The way I achieved this is to manually add the claim to the AccountController's SignInAsync() call:

var claims = new[]
{
    new Claim(AppSettings.Identity.SecurityStampClaimType, user.SecurityStamp)
};

await HttpContext.SignInAsync(userIdString, user.UserName, props, claims);

We deployed these changes to our staging and production servers, and have been able to remain logged in for more than an hour at this point. Considering we were always logged out at around the 30 minute mark before this deployment, I think we can call the issue resolved.

jayoma avatar Sep 19 '18 21:09 jayoma

A standard IS4 + Identity setup does not include this claim in the auth cookie by default.

Do you have this config: https://github.com/IdentityServer/IdentityServer4.AspNetIdentity/blob/dev/src/IdentityServerBuilderExtensions.cs#L44

brockallen avatar Sep 20 '18 13:09 brockallen

The way I achieved this is to manually add the claim to the AccountController's SignInAsync() call:

Ah, this also shows that you''re not using the SignInManager to issue the cookie. It normally adds the security stamp claim.

brockallen avatar Sep 20 '18 13:09 brockallen

Do you have this config: https://github.com/IdentityServer/IdentityServer4.AspNetIdentity/blob/dev/src/IdentityServerBuilderExtensions.cs#L44

Since I'm calling your AddAspNetIdentity extension method, it's adding that config for me.

jayoma avatar Sep 20 '18 15:09 jayoma

Ah, this also shows that you''re not using the SignInManager to issue the cookie. It normally adds the security stamp claim.

I've constructed my AccountController using a cross between your IdentityServer4.Quickstart.Ui and your IdentityServerWithAspIdAndEF example AccountControllers. The Quickstart.Ui has important pieces around mobile login, whereas the other has Identity pieces that the Quickstart doesn't, so I wanted to try and take the pieces I needed from each.

Clearly I'm missing something. In the former example (Quickstart.Ui), you're using the HttpContext.SignInAsync() method to issue the cookie. In the latter, you're only calling the SignInManager.PasswordSignInAsync() method, but I didn't realize that was capable of adding the cookie. Guess I need to dig into this a bit more.

jayoma avatar Sep 20 '18 15:09 jayoma