Azure / Microsoft.Azure.StackExchangeRedis

Azure-specific wrapper for the StackExchange.Redis client library
MIT License
17 stars 14 forks source link

"Invalid token cannot be read" When authenticating with DefaultAzureCredential (User-Assigned Managed Identity) #62

Open jkindwall opened 3 months ago

jkindwall commented 3 months ago

We recently migrated our platform to use User-Assigned Managed Identities for connection to Azure Redis Cache. The following code was added to establish the connection:

        private static async Task<ConnectionMultiplexer> GetConnectionMultiplexerAsync(
            IRedisCacheConnectionSettings connectionSettings)
        {
            ConfigurationOptions configurationOptions = ConfigurationOptions.Parse(connectionSettings.ConnectionString);
            await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(
                new DefaultAzureCredential(new DefaultAzureCredentialOptions()
                {
                    ManagedIdentityClientId = connectionSettings.ManagedIdentityClientId
                }));
            return await ConnectionMultiplexer.ConnectAsync(configurationOptions);
        }

I tested this in our dev environment and it was working with a User Assigned Managed Identity, however, now one of our downstream partners who is using this code is reporting they are getting Exceptions with the error message "Invalid token cannot be read". Its tricky to debug as I can't use a managed identity locally, but all of my investigation suggests they have the managed identity set up correctly. It is assigned to the app service executing this code, and they have configured their environment variables with the correct ClientId.

The exception they are seeing seems to be coming from this line: https://github.com/Azure/Microsoft.Azure.StackExchangeRedis/blob/a1a4bef386ba3fd7ca38f36ea38b20da8f10bced/src/AzureCacheOptions.cs#L92 which implies that an empty, null, or malformed jwt token was obtained. But this doesn't make sense. Shouldn't an exception be thrown before this point if authentication failed to retrieve a valid token. How could we possibly end up with a bad or non-existant jwt token without any exceptions being thrown?

bcgrillo commented 1 month ago

Same here 🙋‍♂️ Have you been able to solve it?

philon-msft commented 1 month ago

Have you tried using

await configurationOptions.ConfigureForAzureWithUserAssignedManagedIdentityAsync(connectionSettings.ManagedIdentityClientId);

rather than

await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(
    new DefaultAzureCredential(new DefaultAzureCredentialOptions()
    {
        ManagedIdentityClientId = connectionSettings.ManagedIdentityClientId
    }));