Search code examples
c#authenticationasp.net-web-apidotnet-httpclientbearer-token

AcquireTokenAsync not returning a new token


My WebAPI application gets a token from a service on start-up. This token is then to be used in a shared HTTP Client to prevent port exhaustion.

When this token is about to expire, I want to get a new one and save it in my service for re-use.

In my implementation, a token is retrieved - however it has the same expiry as the original token:

    // Retrieve the token and assign to AuthenticationResult
    private async Task GetAPIToken()
    {
        AuthenticationContext authContext = new AuthenticationContext(Authority);
        var clientCredential = new ClientCredential(clientId, clientSecret);

        // Same token after multiple calls
        AuthenticationResult = await authContext.AcquireTokenAsync(resourceId, clientCredential).ConfigureAwait(false);
    }

How can I save the latest authentication token?


Solution

  • The issue here was that AuthenticationContext authContext = new AuthenticationContext(Authority); will cache a token and retrieve it if it hasn't expired.

    Disabling the cache and managing the token lifecycle myself works as a solution:

    AuthenticationContext authContext = new AuthenticationContext(Authority, null);