1
votes

Azure access token is returned even with an invalid secret when run in a multithreaded environment.

I've got an integration test that checks to see that an invalid client secret won't pass when getting an Azure access token.

When run in isolation the test passes every time, meaning that an invalid client secret does not return an Azure access token.

However, when run with other integration tests (on multiple threads) this function returns an access token even with an obviously invalid client secret.

I don't see any legitimate reason this would be a cached token for the client id even when specifying a totally invalid client secret.

Note, this behavior does not happen when the client id is invalid.

Is there an explanation for this behavior?

    private async Task<string> GetAccessToken(string authority, string resource, string scope)
    {
        var clientCredential = new ClientCredential(clientId, clientSecret);

        var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
        var result = await context.AcquireTokenAsync(resource, clientCredential);

        Debug.WriteLine("----------------------------------");
        Debug.WriteLine(clientId);
        Debug.WriteLine(clientSecret);
        Debug.WriteLine(result.AccessToken);

        return result.AccessToken;
    }

The debug output is

Debug Trace:
----------------------------------
<...client id...>
invalid secret
<...valid token...>
2

2 Answers

3
votes

This is because your cache still has a valid access token in the cache. ADAL checks the cache first and returns the access token if still valid (not expired). Token cache pivots on client_id as one of the dimensions of the key, so invalid client_id fails as expected. To force the library to use the secret and make a network call, you must delete the token from the cache

0
votes

Clear client credential token like below. This AuthenticationContext cache the credentials. clear them before checking another pair of keys.

  var authenticationContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}/v2.0");
        if (authenticationContext?.TokenCache.Count > 0)
        {
            authenticationContext.TokenCache.Clear();
        }