I have the following code for obtaining a secret from the Azure key vault:
public static async Task<string> GetToken(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(...); //app id, app secret
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
public static string GetSecret(string secretName)
{
KeyVaultClient keyVaultClient = new KeyVaultClient(GetToken);
try
{
return keyVaultClient.GetSecretAsync("my-key-vault-url", secretName).Result.Value;
}
catch(Exception ex)
{
return "Error";
}
}
The error I am getting is "access denied", which (I think) means that the id, secret and the vault's url are fine. However, I don't know what I can do differently to fix this error, is there maybe a setting in the Azure portal which is preventing me from reading a secret?
To fix access denied you need to configure Active Directory permissions. Grant access to KeyVault.
1. Using PowerShell Run next command:
Set-AzureRmKeyVaultAccessPolicy -VaultName 'XXXXXXX' -ServicePrincipalName XXXXX -PermissionsToKeys decrypt,sign,get,unwrapKey
2. Using the Azure portal