且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Azure-使用服务原理向KeyVault进行身份验证将返回未授权的异常

更新时间:2023-12-03 09:24:22

我使用以下代码对其进行了测试,它在我这一方面可以正常工作。 resourceUri是 https://vault.azure.net

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;
}

此外,您还需要向注册的应用添加 Key Vault权限。

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

在Key Vault通道中,您需要向已注册的应用程序或用户添加策略。并且在访问控制中,您需要向已注册的应用程序或用户添加权限。

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.

输出如下: