I'm trying to access KeyVault from an .net Core console application, using a Service Principle (I have the App Id and App Secret). Here's my code:
var client = new KeyVaultClient(GetAccessToken);
var secret = client.GetSecretAsync("https://{keyvaultName}.vault.azure.net", "MySecret").Result;
Which calls back to this function:
private static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var credential = new ClientCredential(clientId: appId, clientSecret: appSecret);
var authResult = await context.AcquireTokenAsync(resource, credential);
return authResult.AccessToken;
}
Calling GetSecretAsync returns an "AccessDenied" exception. Modifying the code to use this callback yeilds an "Unauthorized" exception:
private static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
var credential = new ClientCredential(clientId: appId, clientSecret: appSecret);
**var authResult = await context.AcquireTokenAsync("https://management.core.windows.net/", credential);**
return authResult.AccessToken;
}
I setup the Service Principle by going to Azure > AAD > App Registrations, noted the App Id and password (App Secret) when I setup the Principle.
Then in KeyVault, I added the principle to Access Control (IAM), with contributor rights, but still no joy!
Has anyone come across this scenario before?
Thanks! :)