简体   繁体   English

如何从 azure 应用服务访问密钥库

[英]How to access key vault from azure app service

I have the following approach to connect to the key vault in my code:我有以下方法连接到我的代码中的密钥库:

public static class ConfigurationBuilderExtension
{
    public static IConfigurationBuilder AddKeyVaultconfiguration(this IConfigurationBuilder builder)
    {
        var config = builder.Build();

        string name = config["KeyVault:Name"];
        string clientId = config["KeyVault:ClientId"];
        string clientSecret = config["KeyVault:ClientSecret"];

        Verify.NotNullOrEmpty(name, nameof(name));
        Verify.NotNullOrEmpty(name, nameof(clientId));
        Verify.NotNullOrEmpty(name, nameof(clientSecret));

        builder.AddAzureKeyVault($"https://{name}.vault.azure.net/", clientId, clientSecret);

        return builder;
    }
}

To run this locally, I just adding the user secrets to the project:要在本地运行它,我只需将用户机密添加到项目中:

{
  "KeyVault": {
    "Name": "brajzorekeyvault",
    "ClientId": "xxxx",
    "ClientSecret": "xxxx"
  }
}

This works locally.这在本地有效。

However, how do I use this approach when I publish this to a app service in Azure?但是,当我将其发布到 Azure 中的应用程序服务时,如何使用这种方法? I must in somehow inject the name, clientId and clientSecret?我必须以某种方式注入名称、clientId 和 clientSecret? But I don't know which is the best practice approach to do this?但我不知道这样做的最佳实践方法是什么? Should I create a variable group in Azure devops that consists of these values, and then use these in the piplines?我应该在 Azure devops 中创建一个由这些值组成的变量组,然后在管道中使用它们吗?

You should use a managed identity to access the key vault inside the web app to avoid having to inject a secret.您应该使用托管标识访问 web 应用程序内的密钥保管库,以避免注入密钥。 See this tutorial这个教程

For local development you can link an account in VS that will be used to authenticate against the key vault.对于本地开发,您可以在 VS 中链接一个帐户,该帐户将用于针对密钥保管库进行身份验证。 See the docs查看文档

Using managed identities is best practices, in fact you won't see any offical docs about connecting using the client secret withouth at least a warning to use managed identities.使用托管身份是最佳实践,事实上,您不会看到任何有关使用客户端密码进行连接的官方文档,但至少会警告您使用托管身份。

When we are working with PAAS (Most of resources are PAAS in Azure like App service and KeyVault) in Azure. Most of the time, We do not need to write code or write very less code to access them such as in this case.当我们在 Azure 中使用 PAAS(大多数资源是 Azure 中的 PAAS,如 App 服务和 KeyVault)时。大多数时候,我们不需要编写代码或编写非常少的代码来访问它们,例如在这种情况下。 Do not need to provide any detail like connection string or other details to access key vault in app service, Just do little configuration in azure portal and direct get secret from key vault.无需提供任何详细信息(如连接字符串或其他详细信息)即可访问应用服务中的密钥保管库,只需在 azure 门户中进行少量配置并直接从密钥保管库中获取机密。

In Azure, they are resources in same resource group which can communicate to each other or authenticate or authorize by just adding object id of app service to keyvault "Access policies".在 Azure 中,它们是同一资源组中的资源,只需将应用服务的 object id 添加到 keyvault“访问策略”即可相互通信或进行身份验证或授权。 All the headache is on azure of validation.所有令人头疼的问题都在 azure 的验证上。 It is very easy, secure and good practice.这是非常简单、安全和良好的做法。

Steps are as Follows步骤如下

  1. Enable Managed Service Identity for your Web App/App Service为您的 Web 应用程序/应用程序服务启用托管服务标识

    a.一种。 Select "Identity" from the left-side menu in the Azure Web App/App Service. Select Azure Web 应用程序/应用程序服务中左侧菜单中的“身份”。

    b. b. In the System-assigned tab, Change the "Status" toggle to "On".在“系统分配”选项卡中,将“状态”切换更改为“打开”。

    c. After a few seconds, Object ID will be available then copy the "Object ID". c。几秒钟后,Object ID 将可用,然后复制“对象 ID”。

在此处输入图像描述

  1. Authorize the Web App/App Service to access Your Key Vault授权 Web App/App Service 访问您的 Key Vault

    a.一种。 Select "Access policies" from the "Key Vault" screen. Select 来自“Key Vault”屏幕的“访问策略”。

    b. b. Click "Add Access Policy".单击“添加访问策略”。

    c. Provide the "Get" and "List" permissions. c。提供“获取”和“列表”权限。

    d. d. In the “Select a Principal” option, specify the value for the "Object ID" you copied earlier for the Azure Web App/App Service.在“Select a Principal”选项中,指定您之前为 Azure Web App/App Service 复制的“对象 ID”的值。

    e. e. Paste, search and then select it from the list.粘贴、搜索,然后从列表中搜索 select。

    f. F。 Click "Add".单击“添加”。

    g. G。 Click "Save" to persist the changes and complete the process.单击“保存”以保留更改并完成该过程。

Provide Permissions

在此处输入图像描述

Copy object Id

在此处输入图像描述

  1. Read Azure Key Vault Secrets in .NET Core阅读 .NET Core 中的 Azure Key Vault Secrets

    a.一种。 Install the NuGet Packages安装 NuGet 包

    You may install these packages in one of two ways: Either via the NuGet Package Manager integrated into the Visual Studio 2019 IDE or by running the following command(s) in the Package Manager Console:可以通过以下两种方式之一安装这些软件包:通过集成到 Visual Studio 2019 IDE 中的 NuGet Package 管理器,或通过在 Package 管理器控制台中运行以下命令:

    Install-Package Microsoft.Extensions.Azure and Install-Package Azure.Security.KeyVault.Secrets安装包 Microsoft.Extensions.Azure 和安装包 Azure.Security.KeyVault.Secrets

Note:- In My case, I did not need to install these packages.

b. b. Access Secrets from AzureKeyVault从 AzureKeyVault 访问机密

  1. Specify the Vault Uri in AppSettings:- Create a section named "KeyVault" in the appsettings.json file and specify a key named "VaultUri" in there as shown below.在 AppSettings 中指定 Vault Uri:- 在 appsettings.json 文件中创建一个名为“KeyVault”的部分,并在其中指定一个名为“VaultUri”的密钥,如下所示。

appsettings.Development.json appsettings.Development.json

{
   "SecretName": "xyz"
}

appsettings.OtherEnv.json appsettings.OtherEnv.json

       "KeyVault": {
         "VaultUri": "https://yourkeyvaulturl.vault.azure.net/"
         }
  1. Create KeyVaultManagement class创建 KeyVaultManagement class
public class KeyVaultManagement
   {
      private readonly IConfiguration _config;

      public KeyVaultManagement(IConfiguration config)
      {
        _config= config;
      }

      public SecretClient SecretClient
      {
        get
         {
            return new SecretClient(
                             new Uri($"{this._config["KeyVault:VaultUri"]}"),
                             new DefaultAzureCredential()) ;
         }
       }
  }
  1. Write the below code in Program.cs在 Program.cs 中编写以下代码
.ConfigureAppConfiguration((context, config) =>
{
   var builtConfig = config.Build();
   if (!context.HostingEnvironment.IsDevelopment())
   {
     config.AddAzureKeyVault(new KeyVaultManagement(builtConfig).SecretClient, new KeyVaultSecretManager());
   }
});
  1. Write the below where need to fetch secret.在下面写下需要获取秘密的地方。
var valueofSecret = configuration["SecretName"];

configuration is IConfiguration

Documentation of Microsoft for Access Policy of Azure Keyvault Azure Keyvault 访问策略微软文档

IF YOUR APPLICATION IS NOT APP SERVICE OR IT IS DEVELOPED IN .NET FRAMEWORK如果您的应用程序不是应用程序服务或它是在 .NET 框架中开发的

Then Implement KEYVAULT using Certificate然后使用证书实现 KEYVAULT

  1. Install Same Nuget Packages安装相同的 Nuget 包

  2. Write the below code in Program.cs.在 Program.cs 中编写以下代码。 Might need to add package or namespace to use certificate classes可能需要添加 package 或命名空间才能使用证书类

.ConfigureAppConfiguration((context, config) =>
{
   var root = config.Build();
   var KeyVaultName = root["KeyVaultName"];
   var Uri = new Uri($"https://{KeyVaultName}.vault.azure.net/");
   var x509Certifcate = CertifcateHelper.GetCertificate(root["Thumprint"],"KeyVaultCertificate");
   
     config.AddAzureKeyVault(Uri , new ClientCertificateCredential(root["ClientTenantId"], root["ClientAppId"], x509Certifcate));
});

  1. Add the below lines in APPSetting在 APPSetting 中添加以下行

appsettings.Development.json

{
   "KeyVaultName": "keyvalutname",
   "ClientTenantId": "Get from azure and paste here",
   "ClientAppId": "Get from azure and paste here",
   "Thumbprint": "Get from keyvalut certificate in azure and paste here";
}
  1. Write the below where need to fetch secret.在下面写下需要获取秘密的地方。
var valueofSecret = configuration["SecretName"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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