DEV Community 👩‍💻👨‍💻

Cover image for Connect to an Azure key vault from a program on any laptop using user identity
Antoine
Antoine

Posted on • Updated on

Connect to an Azure key vault from a program on any laptop using user identity

Photo by Jude Beck on Unsplash

Connecting from a Managed Service Identity (MSI) to an Azure Key Vault is pretty well documented. But how can we achieve this from a program on a laptop using user account ?

Azure Active Directory Application

First we will require an application registered to the Azure Active Directory of your subscription, with the right user_impersonation.

Write down, the application identifier, and the redirect uri if any, and the directory identifier of your subscription.

Program

In your program, you will have to:

  • add the package Microsoft.Identity.Client to your application
  • Get the Token from Azure using the following code
            IPublicClientApplication app = PublicClientApplicationBuilder.Create(applicationId)
                                                                        .WithRedirectUri(redirectUri)
                                                                        .WithAuthority($"https://login.microsoftonline.com/{directoryId}")
                                                                        .WithTenantId(directoryId)
                                                                        .Build();
            string[] scopes = new string[] { "https://vault.azure.net/user_impersonation" };
            Microsoft.Identity.Client.AuthenticationResult result = null;
            var accounts = await app.GetAccountsAsync();

            try
            {
                result = await app.AcquireTokenSilent(scopes,
                                                    accounts.FirstOrDefault())
                    .ExecuteAsync();
            }
            catch (MsalUiRequiredException msalUiEx)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilent.
                // This indicates you need to call AcquireTokenInteractive to acquire a token
                //System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {msalUiEx.Message}");

                try
                {
                    result = await app.AcquireTokenInteractive(scopes)
                        .ExecuteAsync();
                    //  Msal.Utils.extractIdToken
                }
                catch (MsalException msalex)
                {
                    throw;
                }
            }

Enter fullscreen mode Exit fullscreen mode
  • then, we can instantiate a keyvault client using the token
            HttpClient client = new HttpClient();
            keyVaultClient = new KeyVaultClient(async (authority, resource, scope) => 
                                                { 
                                                    return result.AccessToken;
                                                }, client);
Enter fullscreen mode Exit fullscreen mode

Note that

  • AcquireTokenInteractive will request from the user to fill its account / password using the configured parameters (using only work and school account or not) in a popup
  • the token is available in result.AccessToken, which will expire at result.ExpiresOn
  • the user account has to have an access policy to the key vault
  • Scopes cannot be combined if it relates to different resources ( "https://vault.azure.net/user_impersonation", "User.Read" can't work for example, 2 calls has to be made)
  • Github issue providing a lot of informations

Hope this helps !

Top comments (0)

Now it's your turn.

 
🗒 Share a tutorial
🤔 Reflect on your coding journey
❓ Ask a question
 
Create an account to join hundreds of thousands of DEV members on their journey.