Table of Contents

Migrate from Arc4u 9.0 to 9.1

This guide is for teams that run an application on Arc4u 9.0 and want to move it to Arc4u 9.1. Arc4u 9.1 changes the token cache: ITokenCache is asynchronous, and the token cache can be chosen per client token and per on-behalf-of setting. Most applications only update the package versions; the changes below concern code that implements, mocks or calls the token cache directly, and a few behaviors of the token providers.

For the complete list of changes, see the changelog.

Who is affected

You… Read
implement ITokenCache, call it, or mock it in tests ITokenCache is asynchronous
implement ICacheHelper ICacheHelper has a named cache method
create ApplicationCache or AzureADOboTokenProvider with new Constructors
use UseBasicAuthentication with your own token provider The Basic authentication middleware no longer caches
catch exceptions of the on-behalf-of provider, or need Windows authentication on the token endpoint On-behalf-of provider
rely on how long the tokens stay in the cache Tokens are cached until they expire
use ApplicationLocalDataCache (desktop or mobile client) The local token cache keeps a token per key
call the Credential provider with settings that may have no Scope Missing settings give a failed result
use OpenID Connect or hybrid authentication (the authentication cookie) The authentication cookie

Nothing changes in the appsettings.json of a 9.0 application: the new sections are optional (see A token cache per client token or on-behalf-of setting).

ITokenCache is asynchronous

The token cache is usually a distributed cache (Redis, SQL Server): its synchronous methods blocked a thread during each round trip. Get, Put and DeleteItem are replaced by asynchronous methods that return a ValueTask and take a CancellationToken. Each method also takes an optional optionsName, the name of the TokenCacheOptions to use (null for the default ones).

Before (9.0)

var token = tokenCache.Get<TokenInfo>(key);
if (token is null)
{
    token = await RequestTokenAsync();
    tokenCache.Put(key, token);
}
tokenCache.DeleteItem(key);

After (9.1)

var token = await tokenCache.GetAsync<TokenInfo>(key, cancellationToken: cancellationToken);
if (token is null)
{
    token = await RequestTokenAsync();
    await tokenCache.PutAsync(key, token, cancellationToken: cancellationToken);
}
await tokenCache.DeleteItemAsync(key, cancellationToken: cancellationToken);

Steps:

  1. Replace the calls as above and await them. Pass the TokenCacheOptionsName value of the settings as optionsName when your code serves a client token or an on-behalf-of setting: settings.Values.TryGetValue(TokenKeys.TokenCacheOptionsName, out var optionsName).
  2. In an implementation of ITokenCache, implement GetAsync, PutAsync and DeleteItemAsync. An implementation with a single store ignores optionsName.
  3. In Moq setups and verifications, match the new arguments: an argument left out matches only its default value.
mock.Setup(m => m.GetAsync<TokenInfo>(It.IsAny<string>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()))
    .ReturnsAsync((TokenInfo?)null);
mock.Verify(m => m.PutAsync(It.IsAny<string>(), It.IsAny<TokenInfo>(), It.IsAny<string?>(), It.IsAny<CancellationToken>()), Times.Once);

ICacheHelper has a named cache method

ICacheHelper has a new method, ICache GetCache(string? cacheName), that returns the cache registered under a name, the token cache when the name is empty, and the default cache when no cache has this name or when the cache cannot be initialized (an unreachable Redis server, for example). The token cache readers call it on every read and write, so resolve each name once. An implementation of ICacheHelper must add it, with the same behavior as CacheHelper:

private readonly ConcurrentDictionary<string, ICache> _namedCaches = new(StringComparer.Ordinal);

public ICache GetCache(string? cacheName)
    => string.IsNullOrWhiteSpace(cacheName)
        ? GetCache()
        : _namedCaches.GetOrAdd(cacheName, name =>
        {
            try
            {
                if (_cacheContext.Exist(name))
                {
                    return _cacheContext[name];
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "The token cache {CacheName} cannot be initialized: the default cache is used.", name);
            }

            return _cacheContext.Default;
        });

A mock of ICacheHelper that only sets up GetCache() keeps working for the default options.

Note

A named cache that cannot be initialized when it is first used is replaced by the default cache until the application restarts, as the token cache already is.

Constructors

The dependency injection fills the new parameters; only code that creates these classes with new changes.

Class 9.1 constructor
ApplicationCache Takes (ILogger, TokenCacheResolver) instead of (ICacheHelper, ILogger, IOptions<TokenCacheOptions>).
AzureADOboTokenProvider Adds the optional IHttpClientFactory? and TokenCacheResolver? at the end.

TokenCacheResolver is a singleton registered by AddTokenCache, AddJwtAuthentication, AddClientTokens, AddOnBehalfOf, AddOnBehalfOfSettings and AddBasicAuthenticationSettings. If you register ApplicationCache yourself without any of them, call services.AddTokenCacheResolver(). Take it from the container:

var tokenCache = new ApplicationCache(logger, serviceProvider.GetRequiredService<TokenCacheResolver>());

The Basic authentication middleware no longer caches

UseBasicAuthentication cached the token it got for a Basic credential, and the default Credential provider (CredentialTokenCacheTokenProvider) cached the same token again under another key. In 9.1 the middleware asks the provider named by Authentication:Basic:Settings:ProviderId on every request, and the provider is responsible for caching.

  • With the default Credential provider, nothing changes for you: the token is stored once instead of twice.
  • With your own provider, make it cache the token, for example in the ITokenCache, or the token endpoint is called on every request.

On-behalf-of provider

AzureADOboTokenProvider changes in three ways.

Errors are returned, not thrown. An error status code of the token endpoint, and a missing ClientId, ClientSecret or Scope, give a failed Result instead of an HttpRequestException or a KeyNotFoundException. Replace a try/catch around GetTokenAsync with a check of the result:

var result = await provider.GetTokenAsync(settings, null);
if (result.IsFailed)
{
    // The errors describe the failure, for example the status code of the token endpoint.
}

No Windows credentials, and no HttpClient per request. The provider no longer sends the Windows credentials of the process (UseDefaultCredentials) to the token endpoint. It uses the default client of the IHttpClientFactory when one is registered, and otherwise a shared HttpClient. If your token endpoint needs Windows authentication, configure it on a named client and give its name in the new HttpClientName of the on-behalf-of setting:

builder.Services.AddHttpClient("Sts")
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { UseDefaultCredentials = true });
"OnBehalfOf": {
  "Inventory": { "ClientId": "<client-id>", "ClientSecret": "<client-secret>", "Scopes": [ "api://inventory/.default" ], "HttpClientName": "Sts" }
}

Tokens are kept at most MaxTime. See the next section. An expires_in larger than one year is read as one year, and a negative one as zero (the token is returned but not cached). A token valid for one minute or less is returned but not cached either: a cached token is used only when it is valid for more than one minute.

Tokens are cached until they expire

ApplicationCache.PutAsync keeps a TokenInfo until the first of its ExpiresOnUtc and the MaxTime of its TokenCacheOptions (50 minutes by default); 9.0 always used MaxTime. An expired token is not stored, and the entry already stored under the key is removed. The ClientCredentials and Credential providers do not cache a token valid for less than one minute: they serve a cached token only when it is valid for at least one minute.

AddTokenCache now rejects a negative Authentication:TokenCache:MaxTime with a ConfigurationException at startup, as it already did for zero.

The on-behalf-of provider now applies MaxTime too, as ApplicationCache does: in 9.0 it kept a token until it expired. With tokens that live longer than MaxTime (Azure AD issues tokens of 60 to 90 minutes), the on-behalf-of token is requested again a little earlier. Raise Authentication:TokenCache:MaxTime, or give the on-behalf-of setting its own TokenCache, to keep the 9.0 behavior.

The local token cache keeps a token per key

ApplicationLocalDataCache kept one token in memory and returned it for any key: a second key got the token of the first one, and deleting any key cleared it. In 9.1 each key keeps its own token, and DeleteItemAsync (or Clear) removes only its key.

  • An application that stores one token under one key sees no change.
  • An application that read the token under another key than the one it was stored under now gets null for that key (the value of the secure cache): read it with the key it was stored under.

Missing settings give a failed result

CredentialTokenCacheTokenProvider (the Credential provider) returns a failed Result that names the missing Scope instead of throwing a KeyNotFoundException, as the other errors of its settings. Check the result instead of catching the exception.

The authentication cookie of OpenID Connect and hybrid authentication is now always issued with Path=/ and no Domain. In 9.0 its path followed the request path base, so an application behind UsePathBase or a branch mapping got Path=/<base>; it now gets Path=/.

CookieName is still required, and the __Host- prefix is not mandatory: a name without it, such as MyApp, keeps working as in 9.0. Arc4u only logs warning 9152 at startup to recommend the prefix, which keeps a sibling subdomain from planting a cookie of the same name. To follow the recommendation:

  • rename the cookie, for example "CookieName": "__Host-MyApp", or
  • keep the name and set "AddHostPrefixToCookieName": true in the Authentication section: Arc4u then issues MyApp as __Host-MyApp.

Either way the cookie gets a new name, so every user is signed out once after the deployment. If that is not acceptable now, keep the current name and accept the warning.

A token cache per client token or on-behalf-of setting

This is new and optional. An entry of Authentication:ClientTokens or Authentication:OnBehalfOf can set its own TokenCache, and the Authentication:ClientTokensCache and Authentication:OnBehalfOfCache sections set the token cache of every entry of their section. Each value is taken from the entry, then from the shared section, then from Authentication:TokenCache.

{
  "Authentication": {
    "TokenCache": { "CacheName": "Volatile", "MaxTime": "00:40:00" },
    "ClientTokensCache": { "CacheName": "Redis" },
    "ClientTokens": {
      "Inventory": {
        "Scenario": "ClientCredentials",
        "Settings": { "ClientId": "<client-id>", "ClientSecret": "<client-secret>" },
        "TokenCache": { "MaxTime": "00:05:00" }
      }
    }
  }
}

When a shared section exists, no entry of its section can be named like it (ClientTokensCache or OnBehalfOfCache). To give your own entries a shared section, use AddNamedTokenCache and AddSharedTokenCache. See Choose the token cache of an entry.

The on-behalf-of tokens stay in the index of the user, now with the name of their cache, so the sign-out removes each token from its own cache, even when its options were changed or removed since the token was cached. An index stored by 9.0 is still read: no cache has to be cleared when you deploy.