0
votes

I'm experimenting with various Azure features and currently want to retrieve a secret from KeyVault.

Straight to the case:

I'm using this nuget package to interact with my azure resources.

I've developed a simple .NET Core console app and run it locally.

I have a KeyVault resource with one secret defined which is active and not expired.

I've registered an App in AAD so my locally shipped .NET Core console app has an identity within AAD.

Than I've created a "client secret" within this registered app in AAD to use it to authenticate myself as an app.

After that I've added access policy in my KeyVault resource to allow GET operation for secrets for this registered app: KeyVault access policies

Then I've developed a small piece of code which should retrieve the desired secret:

public class AzureAuthentication
{
    public async Task<string> GetAdminPasswordFromKeyVault()
    {
        const string clientId = "--my-client-id--";
        const string tenantId = "--my-tenant-id--";
        const string clientSecret = "--my-client-secret--";
        var credentials = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var client = new SecretClient(new Uri("https://mykeyvaultresource.vault.azure.net"), credentials);
        var secret = await client.GetSecretAsync("admincreds");
        return secret.Value.Value;
    }
}

However when I'm trying to do this I'm getting an AccessDenied error: error

Am I missing something painfully obvious here? Or there is some latency (>30 min for this moment) for which changes from Access policies screen in KeyVault resource are applied?

2
Hi @JoyWang, I've just recreated the whole case and you are right. I was setting myself (my account) as a principal and then my app as an "authorized application". When I set my app as a principal then it worked. Many thanks! - Kamil Stadryniak

2 Answers

1
votes

I test your code and Get permission, it works fine.

enter image description here

From your screenshot, it looks you didn't add the correct service principal related to the AD App to the Access policies.

If you add the service principal related to the AD App, it will appear as APPLICATION, not COMPOUND IDENTITY.

enter image description here

enter image description here

So when you add it, you could search for the client Id(i.e. application Id) or the name of your App Registration directly, make sure you add the correct one.

enter image description here

1
votes

Make sure your AD App(service principal) has the correct permission in your keyvault -> Access policies