Azure - authenticating to KeyVault using Service Principle returns an Unauthorized exception

Deadly 提交于 2019-12-05 10:10:17

I test it with the following code, it works correctly on my side. The resourceUri is https://vault.azure.net.

static string appId = "xxxxxxxxxxxxx";
static string appSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
static string tenantId = "xxxxxxxxxxxxxxxxxxxxx";
public static void Main(string[] args)
{
    var kv = new KeyVaultClient(GetAccessToken);
    var scret = kv.GetSecretAsync("https://xxxxxx.vault.azure.net", "secretname").GetAwaiter().GetResult();
}

public static async Task<string> GetAccessToken(string azureTenantId, string clientId, string redirectUri)
{
    var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
    var credential = new ClientCredential(appId, appSecret);
    var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", credential);
   return tokenResult.AccessToken;
}

Also, you need to add permission with "Key Vault" to the registered app.

In Key vault channel, you need to Add policies to your registered application or user. And in Access Control you need to add permission to your registered application or user.

The output is as below:

"Access Control (IAM)" controls access to the vault itself. There is a separate way to control access to the contents of the vaults (i.e.: the keys, secrets, and certificates). As mentioned in these docs, we can authorize a given AAD application to retrieve secrets in a given vault in the Azure Portal by navigating to the desired vault, selecting "Access policies", clicking on "Add new", and then searching for your service principal. You should be able to filter by application ID:

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