使用C#的Azure Key Vault添加访问策略

时间:2020-04-21 15:24:03

标签: c# azure-keyvault

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

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

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

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

但是,首先,我需要使用“列表”和“获取”权限来设置访问策略。在PowerShell中,我可以通过以下方式实现这一点:

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

您知道我可以在C#中执行相同操作的方法吗?

1 个答案:

答案 0 :(得分:1)

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

  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" 

enter image description here

  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();