Use KeyVaultClient with MSAL Token “Unauthorized”

眉间皱痕 提交于 2021-02-10 18:50:50

问题


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:


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.

2.Click API permissions->click add permission.

3.choose azure key vault.

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



来源:https://stackoverflow.com/questions/55517910/use-keyvaultclient-with-msal-token-unauthorized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!