DEV Community

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

Posted on • Edited 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 !

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay