asp.net-coreauthenticationopenid-connect

In ASP.NET Core OpenIdConnect authentication, how can I keep the cookie state in sync with the ID token?


In ASP.NET Core docs, the following code is used as an example of setting up the OIDC authentication:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    var oidcConfig = builder.Configuration.GetSection("OpenIDConnectSettings");

    options.Authority = oidcConfig["Authority"];
    options.ClientId = oidcConfig["ClientId"];
    options.ClientSecret = oidcConfig["ClientSecret"];

    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.ResponseType = OpenIdConnectResponseType.Code;

    options.SaveTokens = true;
    options.GetClaimsFromUserInfoEndpoint = true;

    options.MapInboundClaims = false;
    options.TokenValidationParameters.NameClaimType = JwtRegisteredClaimNames.Name;
    options.TokenValidationParameters.RoleClaimType = "roles";
});

The OIDC server returns three tokens: access_token, refresh_token and id_token. The SaveTokens option saves these tokens in the cookie. After one hour the tokens will expire, but as far as I know the cookie session will stay valid.

So here are my questions: What needs to be done after one hour? Where do I need to refresh my tokens? In a background job or in a HTTP request? The refresh result could fail or succeed, how can I update the cookie session with the new result?

Unfortunately the documentation does not clarifies these concepts.


Solution

  • There is no built-in logic to do that in ASP.NET Core.

    So, you need to write the logic to refresh the access token yourself or use a third-party library like Duende.AccessTokenManagement to do it for you.

    Also, it important to realise that the cookie lifetime is independent of the tokenlifetime and optinally, you can "SignIn" the user again when you receive a new ID-token or just keep it as it is.