Tuesday, May 25, 2021

Authenticating using Azure SDK

Introduction: The previous article mentioned the way to use the new Azure.Identity credentials with the Fluent library from Azure. This article describes the use of DefaultAzureCredential for the logged-in user.  

Description: The DefaultCredential class in the previous versions of the SDK and the DefaultAzureCredential in the current version of the SDK both support common developer workflows. The DefaultAzureCredential in the Azure SDK is the recommended way to handle the authentication across the local workstation and the deployment environment. It is really automation to finding the right credential to use. It uses the most appropriate credential to use by iterating through four specific locations. These are environment variables, managed identity, the MSAL shared token cache, and the Azure CLI. The environment variables used are AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID. Once these are set and used, other credentials can be read from the key-vault store. It is also possible to bring up an interactive browser for login with SDKs specific to some languages. Credentials once formed can be stored in encrypted locations reducing the exposure to others. The DefaultAzureCredentials supports and attempts to authenticate with a few more such as VisualStudioCredential, SharedTokenCacheCredential, and InteractiveBrowserCredential. The VisualStudioCredential is an integration with the Azure Account Extension and is the same one used with the “Azure Sign in” command. 

It is also possible to exclude some credentials. This is done with the help of DefaultAzureCredentialOptions where there are flags to exclude every one of the credentials mentioned. 


There is also a technique to fail the authentication and not try the next. This is done with the help of the CredentialUnavailableException.DefaultAzureCredential exception type. When it is added, then the next credential is tried only when CredentialUnavailableException is thrown from the current credential. If a different exception is thrown then it is propagated and the next one is not tried. 


Connecting to a client with the DefaultAzureCrendential is a breeze. Let’s review the syntax: 

In .Net: 

var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential(true)); 


And in Java: 

SecretClient client = new SecretClientBuilder() 

        .vaultUrl(keyVaultUrl) 

        .credential(new DefaultAzureCredentialBuilder().build()) 

        .buildClient(); 

No comments:

Post a Comment