【问题标题】:Create Azure Key Vault Using .Net Core 2.1使用 .Net Core 2.1 创建 Azure Key Vault
【发布时间】:2021-06-16 22:31:44
【问题描述】:

我正在尝试使用带有 OpenIdConnect 的 .net core 2.1 创建 azure key vault。

我尝试过的:-
我已经尝试参考以下堆栈溢出问题的答案

  1. Creating Azure Key Vault using .NET assembly (Microsoft.Azure.KeyVault)
  2. Azure Key Vault - programmatic creation

其他

Nuget 包:- Microsoft.Azure.Management.KeyVault

代码:-

private async Task AddKeyVaultAsync()
    {
        var clientId = "xxxx"; 
        var tenantId = "xxxx";
        var clientSecret = "xxxx";
        var objectId = "xxxx";
        var subscriptionId = "xxx";

        // The resource group to create the vault in.
        string resourceGroupName = "Vaults-Resource-Group";
        // The name of the vault to create.
        string vaultName = "web-app-01-vault";
        var parameters = new VaultCreateOrUpdateParameters()
        {
            Location = "southeast asia",
            Properties = new VaultProperties()
            {
                TenantId = Guid.Parse(tenantId),
                AccessPolicies = new List<AccessPolicyEntry>()
                {
                    new AccessPolicyEntry
                    {
                        TenantId = Guid.Parse(tenantId),
                        ObjectId = objectId,
                         Permissions = new Permissions
                            {
                              Secrets = new List<string> { "all" },
                              Keys = new string[] { "all" }
                            }
                    }
                }       
            }
        };

        //problem in following line
        var tokenCredentials = new TokenCloudCredentials(subscriptionId, token);

        var keyVaultManagementClient = new KeyVaultManagementClient(tokenCredentials);
        // Create the vault
       await keyVaultManagementClient.Vaults.CreateOrUpdateAsync(resourceGroupName, vaultName, parameters);

    }

但我被困在了

 //problem in the following line
        var tokenCredentials = new TokenCloudCredentials(subscriptionId, token);

如何创建令牌(TokenCloudCredentials 中的参数)和 TokenCloudCredentials? 我应该使用哪个 Nuget 包来创建 TokenCloudCredentials?

我也试过用:-

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
        .Create(clientId)
        .WithTenantId(tenantId)
        .WithClientSecret(clientSecret)
        .Build();

创建 KeyVaultManagementClient。但我不确定该怎么做?

还有其他(更好的)方法来创建 KeyVaultManagementClient 吗?

【问题讨论】:

    标签: c# azure azure-keyvault


    【解决方案1】:

    代码展示了如何使用客户端凭据流获取访问令牌。

    var app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
               .WithAuthority(AzureCloudInstance.AzurePublic, "{tenantID}")
               .WithClientSecret(config.ClientSecret)
               .Build();
    
    string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
    
    var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
    
    var token = result.accessToken;
    

    更多详情请见here


    更新:

    使用 .net core 2.1 创建密钥库的sample

    【讨论】:

    • TokenCloudCredentials 需要哪个 nuget 包?
    • TokenCloudCredentials 需要 @HarishShisode 包 Microsoft.WindowsAzure.Common
    • 您好,上面提到的包与.net core 2.1不兼容。
    • @HarishShisode TokenCloudCredentials 用于旧版本,不再更新。因此,如果您想使用 .net core 2.1 创建密钥保管库,您可以关注此sample
    • 谢谢!以上示例帮助我解决了问题!
    【解决方案2】:
    • 在从代码访问 Key Vault 之前,请确保在 Azure 中配置了 MSI(托管服务标识)

    • 要启用 Azure Key Vault,您需要在下面安装 包。

    PM> Install-Package Azure.Security.KeyVault.Secrets
    PM> Install-Package Microsoft.Extensions.Configuration.AzureKeyVault
    PM> Install-Package Azure.Identity
    PM> Install-Package Azure.Extensions.AspNetCore.Configuration.Secrets
    
    • 在 Program.cs 中启用应用程序配置 — 更新 CreateWebHostBuilder 方法通过调用 config.AddAzureAppConfiguration() 方法。
    #region Imports
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Azure.KeyVault;
    using Microsoft.Azure.Services.AppAuthentication;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.AzureKeyVault;
    using Microsoft.Extensions.Hosting;
    #endregion
    
    namespace AzureKeyVaultLabs.Web
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureAppConfiguration((context, config) =>
                    {
                        var settings = config.Build();
    
                        if (!context.HostingEnvironment.IsDevelopment())
                        {
                            var keyVaultEndpoint = settings["AzureKeyVaultEndpoint"];
    
                            if (!string.IsNullOrEmpty(keyVaultEndpoint))
                            {
                                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                                var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                                config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager());
                            }
                        }
               }
          }
    
    • 对于 Azure 函数应用程序
    public class Startup : FunctionsStartup
        {
            public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
            {
                if (builder != null)
                {
                    //give your app configuration store endpoint
                    string connectionString = Environment.GetEnvironmentVariable("AppConfigurationConnectionString");
                    if (!string.IsNullOrEmpty(connectionString))
                    {
                        builder.ConfigurationBuilder.AddAzureAppConfiguration(connectionString);
                    }
    
                    var settings = builder.ConfigurationBuilder.Build();
                    var keyVaultEndpoint = settings["VaultName"];// Add key vault name in configuration
                    if (!string.IsNullOrEmpty(keyVaultEndpoint))
                    {
                        builder.ConfigurationBuilder
                            .SetBasePath(Environment.CurrentDirectory)
                            .AddAzureKeyVault(new Uri(keyVaultEndpoint), new DefaultAzureCredential())
                            .AddEnvironmentVariables()
                        .Build();
                    }
                }
            }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2018-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2020-05-23
      • 2020-05-04
      相关资源
      最近更新 更多