简体   繁体   中英

How to get a TokenCredential from a ServiceClientCredential object?

In my application, we presently are using ServiceClientCredentials from Microsoft.Rest. We are migrating parts of our application over to start using Azure.ResourceManager 's ArmClient .

Basically all of our previous application integrations into Azure were using Microsoft.Azure.ResourceManager , which exposed agents like BlobClient or SecretClient , and these all accepted ServiceClientCredentials as a valid token type.

Now, with ArmClient I need to authenticate using DefaultAzureCredential which derives from Azure.Core 's TokenCredential .

Surprisingly I haven't been able to find any examples yet of how to create this TokenCredential .

DefaultAzureCredential just works on my local PC since I'm signed into Visual Studio, but not on my build pipeline where I use Certificate based auth exposed as a ServiceClientCredential .

This was easier than I thought. The fix ended up being adding a new ServiceCollection extension method and passing in IWebHostEnvironment.

I use that to determine whether running in local debug, in which case we can use DefaultAzureCredential, or whether running in prod mode, in which case we should use Certificate Based auth.

It looks somewhat like this and works like a charm.

public static IServiceCollection AddDefaultAzureToken (this IServiceCollection services, IWebHostEnvironment environment)
{
        if (environment.IsDevelopment())
        {
            var l = new DefaultAzureCredential();
            services.AddSingleton<TokenCredential, l>;
        }
        else
        {
            var certCredential= new ClientCertificateCredential(null, null, "Abc");
            services.AddSingleton<TokenCredential, certCredential>;
        }

        return services;
}

This works since DefaultAzureCredential and ClientCertficateCredential all have a common ancestor of TokenCredential, and the L in SOLID, the Liskov Substitution principle tells us that any implementation of a class can be substituted for any other instance of that class without breaking the application.

Note: the above sample was pseudocode and may need slight changing to work in your environment and should be cleaned to match your teams coding standards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM