1
votes

How can a desktop application use Azure AD to read KeyVault secrets?

I am able to acquire a MSAL token but handing it to KeyVaultClient always results in:

Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: Operation returned an invalid status code 'Unauthorized'

I'm not even sure KeyVault supports this kind of token but in my Googling I've seen examples of the older ADAL tokens being used.

My KeyVault has access policies for both my Azure AD account and a group I'm a member of.

The payload of the JWT token I get back from MSAL has these scopes:

"scp": "User.Read profile openid email"

Here is a mcve:

public partial class MainWindow : Window
{
    private static string ClientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
    public static PublicClientApplication PublicClientApp = new PublicClientApplication(ClientId);

    public MainWindow()
    {
        InitializeComponent();
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        var secret = await GetKeyVaultSecret("TestSecret");
    }

    private async Task<string> GetKeyVaultSecret(string secretKey)
    {
        KeyVaultClient kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(AcquireMSALToken));

        try
        {
            var secretBundle = 
                await kvClient.GetSecretAsync("https://xxxxx.vault.azure.net/", 
                    secretKey, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

            return secretBundle.Value;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
            return null;
        }
    }

    private static async Task<string> AcquireMSALToken(string authority, string resource, string scope)
    {
        string[] _scopes = new string[] { "user.read" };

        AuthenticationResult authResult = null;
        var app = PublicClientApp;
        var accounts = await app.GetAccountsAsync();

        try
        {
            authResult = await app.AcquireTokenSilentAsync(_scopes, accounts.FirstOrDefault());
            return authResult.AccessToken;
        }
        catch (MsalUiRequiredException)
        {
            try
            {
                authResult = await PublicClientApp.AcquireTokenAsync(_scopes);
                return authResult.AccessToken;
            }
            catch (MsalException) { throw; }
        }
        catch (Exception) { throw; }
    }
}

UPDATE

FYI, this works but I don't think this is what the AzureServiceTokenProvider is meant for based on the docs. It leads me to believe the MSAL token is not compatible with KeyVault. My feeling is it is only used for MS Graph calls.

using Microsoft.Azure.Services.AppAuthentication;

AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));


var secretBundle =  await kvClient.GetSecretAsync("https://xxxxxxxx.vault.azure.net/",
                    "TestSecret", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

return secretBundle.Value;
1
Does it work if you acquire the token and register and add permissions to the app as described here? - mm8
I have my app registered but I don't use a client secret because I don't see the point of showing the secrets in source code if I"m going to the trouble to use a KeyVault. I was hoping the token identified the user and KeyVault would allow it if it had an Access Policy for the user. - Crowcoder

1 Answers

4
votes

The scopes are not correct for accessing Azure key vault. You should use

string[] _scopes = new string[] { "https://vault.azure.net/.default" };

You can add specific permissions as you like.

Normally you need to fully qualify every scope, but MS Graph API is a special case. It allows you to use the "short form" like {user.read}.

You can follow these steps to grant permissions to the application.

1.Click App registrations(preview)->Click the application you registered.

enter image description here

2.Click API permissions->click add permission.

enter image description here

3.choose azure key vault.

enter image description here

4.click grant admin consent at the bottom of API permissions page.

enter image description here