c# - 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# 中做同样的事情吗?
解决方案
如果要使用 Net 管理 Azure Key Vault 访问策略,请参考以下步骤
- 创建服务主体(我使用 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"
- 代码
// 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();
推荐阅读
- python - 无法在 Python 中导入模块?
- html - 如何使用 React 从打字稿中的对象创建 HTML 元素
- reactjs - Redux 存储在向我的 reducer 发送操作后不更新
- java - 对不同类型的对象具有相同验证规则的 Java 设计类
- javascript - 如何展平嵌套对象?
- ssis - 具有本地 C 驱动器与网络驱动器的 SSIS 包文件
- postgresql - 如何在rails 5中添加具有较低功能的三元组索引
- postgresql - 将 postgres 参数传递到 Kubernetes 部署中
- python - 寻找一种将行组合在一起的方法,以便在 Python/Pandas 中列匹配并且一列的数字大于或等于零
- heroku - DNS 目标和路由问题