2

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;
Tony Ju
  • 14,891
  • 3
  • 17
  • 31
Crowcoder
  • 11,250
  • 3
  • 36
  • 45
  • Does it work if you acquire the token and register and add permissions to the app as described [here](https://stackoverflow.com/a/53179324/7252182)? – mm8 Apr 04 '19 at 15:15
  • 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 Apr 04 '19 at 15:26

1 Answers1

4

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

Tony Ju
  • 14,891
  • 3
  • 17
  • 31
  • I can't tell if this is the solution yet but it looks promising. I'm now getting "Need admin approval..." dialog which I thought was already granted. – Crowcoder Apr 08 '19 at 12:26
  • Based on the error message, you should go to a URL such as https://login.microsoftonline.com/tenant-id/oauth2/authorize?client_id=app-client-id&redirect_uri=encoded-reply-url&response_type=code&prompt=admin_consent Use your admin account to consent the permissions. @Crowcoder – Tony Ju Apr 08 '19 at 12:37
  • @Crowcoder you can check on azure portal if you have already granted admin permission to your application – Tony Ju Apr 08 '19 at 12:42
  • Unfortunately I"m not admin in azure so I have to get help from infrastructure team. – Crowcoder Apr 08 '19 at 12:47
  • @Crowcoder Hmm, I have updated my answer. Can you check it? – Tony Ju Apr 08 '19 at 12:52
  • Where/How do you set that grant? – Crowcoder Apr 08 '19 at 12:55
  • @Crowcoder I have updated the answer with the steps. – Tony Ju Apr 08 '19 at 13:03
  • I see, you have to hit the button again if you add new permissions. Thank you! – Crowcoder Apr 08 '19 at 13:06