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;