首页 > 解决方案 > Azure Key Vault 使用 C# 添加访问策略

问题描述

我正在尝试从 Key Vault 中检索所有证书、密钥和机密,以便对其设置执行合规性测试。我能够使用 Azure 管理 SDK 创建 Key Vault 客户端,

KeyVault Client objKeyVaultClient = new KeyVaultClient(
                                                            async (string authority, string resource, string scope) =>
                                                           {
                                                                ...
                                                           }
                                                      );

并尝试通过以下方式检索证书/密钥/机密:

Task<IPage<CertificateItem>> test = objKeyVaultClient.GetCertificatesAsync(<vaultUri>);

但是,首先我需要设置具有 List 和 Get 权限的访问策略。在 PowerShell 中,我通过以下方式实现了这一点:

Set-AzKeyVaultAccessPolicy -VaultName <VaultName> -UserPrincipalName <upn> -PermissionsToKeys List,Get

你知道我可以在 C# 中做同样的事情吗?

标签: c#azure-keyvault

解决方案


如果要使用 Net 管理 Azure Key Vault 访问策略,请参考以下步骤

  1. 创建服务主体(我使用 Azure CLI 来执行此操作)
az login
az account set --subscription "<your subscription id>"
# the sp will have Azure Contributor role
az ad sp create-for-rbac -n "readMetric" 

在此处输入图像描述

  1. 代码
 // please install sdk Microsoft.Azure.Management.Fluent
 private static String tenantId=""; // sp tenant
    private static String clientId = ""; // sp appid

    private static String clientKey = "";// sp password
    private static String subscriptionId=""; //sp subscription id

 var creds=   SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId,clientKey,tenantId,AzureEnvironment.AzureGlobalCloud);
var azure = Microsoft.Azure.Management.Fluent.Azure
                .Configure()
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                .Authenticate(creds)
                .WithSubscription(subscriptionId);

var vault = await azure.Vaults.GetByResourceGroupAsync("group name", "vault name");
await vault.Update().DefineAccessPolicy()
                             .ForUser("userPrincipalName")
                             .AllowKeyPermissions(KeyPermissions.Get)
                             .AllowKeyPermissions(KeyPermissions.List)
                             .Attach()
                          .ApplyAsync();

推荐阅读