David Mason
David Mason

Reputation: 1437

Azure MSAL: Using the Token cache with client credentials

The way I am obtaining a token for my apps looks currently like this:

        IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(_clientId)
           .WithClientSecret(_clientSecret)
           .WithAuthority(new Uri(_authority))
           .Build();
        var result = await app.AcquireTokenForClient("MY SCOPES ARRAY").ExecuteAsync();

But everytime I call "AcquireTokenAsync" another token is returned.
This means that there is no token cache used, but each single request to my APIs will also receive another token.
This is not necessary.

How can I configure the "ClientCredentialsTokenAcquisitionClient" to make use of a token cache?

Reading the official docs from Microsoft tells me only about a user token cache.
So if I am acquiring a token silently in the name of a user I know how to cache my tokens. But how to do this with confidential clients?

I want to prevents thousands of unnecessary calls to the token endpoint of MS.

Upvotes: 0

Views: 3179

Answers (2)

Rich
Rich

Reputation: 1

What worked for my scenario (.NET 6 implementation of a ASP.NET MVC API client credentials auth flow) was taken from the MS code sample here

Using Microsoft.Identity.Web 2.13.2 nuget package at time of writing

Added the statement app.AddInMemoryTokenCache(); before the call to AcquireTokenForClient method.

I was able to confirm that there were no external calls to Azure Security Token Service (Id provider we were using) during the lifetime of the unexpired access token.

I was skeptical about the effects of calling AddInMemoryTokenCache before every call to AcquireTokenForClient but it seems it's idempotent and has no effect on the desired outcome (valid tokens are issued from in memory application token cache until they expire).

Upvotes: 0

Thalles Noce
Thalles Noce

Reputation: 806

Have you included this call in your setup ? It tells the library to cache the token. You can implement it in many ways, here is one example.

services.AddMemoryCache();

Upvotes: 2

Related Questions