Search code examples
c#azure-ad-msal

Does AcquireTokenForClient (MSAL) use the token cache?


I am (successfully) using client credential flow with MSAL to authenticate an app like this:

private static async Task<AuthenticationResult> getAuthResultNonInteractively()
{
    string[] scopes = {"api://xxx/.default"};

    IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(
            new ConfidentialClientApplicationOptions
            {
                TenantId = "xxx",
                ClientId = "xxx",
                RedirectUri = "http://localhost",
                ClientSecret = "xxx"
            })
        .Build();
    
    // Desired behaviour: acquires token online only if token does not 
    // exist in cache or is expired
    AuthenticationResult authResult = await app.AcquireTokenForClient(scopes)
        .ExecuteAsync();

    return authResult;
}

Does the call to AcquireTokenForClient first try to find the token in the token cache, and acquires it online only if the token doesn't exist in the cache yet or the token is expired? Or does it always acquire the token online? If the latter is true, what do I need to change in order to get the desired behavior?


Solution

  • The AppTokenCache used by AcquireTokenForClient is associated with your specific instance of IConfidentialClientApplication, so in order to take advantage of token caching, your IConfidentialClientApplication will need to be long-lived (i.e. singleton).