简体   繁体   中英

Azure Key Vault Add Access Policy with C#

I am trying to retrieve all the Certificates, Keys and Secrets from a Key Vault in order to perform a compliance test of it´s settings. I was able to create a Key Vault Client using Azure Management SDK,

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

and trying to retrieve the certificates / keys / secrets with:

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

However, first I need to set the access policies with List and Get permissions. In PowerShell I achieve this with:

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

Do you know a way that I can do the same in C#?

If you want to manage Azure key vault access policy with Net, please refer to the following steps

  1. create a service principal (I use Azure CLI to do that)
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. Code
 // 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM