您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

为应用服务和 Azure Functions 使用 Key Vault 引用Use Key Vault references for App Service and Azure Functions

备注

Key Vault 引用目前在 Linux 消耗计划中不可用。Key Vault references are not currently available in Linux consumption plans.

本主题介绍在不需进行任何代码更改的情况下,如何使用应用服务或 Azure Functions 应用程序的 Azure Key Vault 中的机密。This topic shows you how to work with secrets from Azure Key Vault in your App Service or Azure Functions application without requiring any code changes. Azure Key Vault 是一项服务,可以提供集中式机密管理,并且可以完全控制访问策略和审核历史记录。Azure Key Vault is a service that provides centralized secrets management, with full control over access policies and audit history.

授予应用对 Key Vault 的访问权限Granting your app access to Key Vault

若要从 Key Vault 读取机密,需创建一个保管库并授予应用访问该保管库的权限。In order to read secrets from Key Vault, you need to have a vault created and give your app permission to access it.

  1. 按照 Key Vault 快速入门中的说明创建一个密钥保管库。Create a key vault by following the Key Vault quickstart.

  2. 为应用程序创建一个系统分配托管标识Create a system-assigned managed identity for your application.

    备注

    Key Vault 引用目前仅支持系统分配托管标识。Key Vault references currently only support system-assigned managed identities. 不能使用用户分配标识。User-assigned identities cannot be used.

  3. 在 Key Vault 中为此前创建的应用程序标识创建一项访问策略Create an access policy in Key Vault for the application identity you created earlier. 在此策略上启用“获取”机密权限。Enable the "Get" secret permission on this policy. 请勿配置“授权的应用程序”或 applicationId 设置,因为这与托管标识不兼容。Do not configure the "authorized application" or applicationId settings, as this is not compatible with a managed identity.

    备注

    Key Vault 引用目前不能解析密钥保管库中存储的具有网络限制的机密。Key Vault references are not presently able to resolve secrets stored in a key vault with network restrictions.

引用语法Reference syntax

Key Vault 引用采用 @Microsoft.KeyVault({referenceString}) 格式,其中 {referenceString} 将替换为下述选项之一:A Key Vault reference is of the form @Microsoft.KeyVault({referenceString}), where {referenceString} is replaced by one of the following options:

引用字符串Reference string 描述Description
SecretUri=secretUriSecretUri=secretUri SecretUri 应该是 Key Vault 中机密的完整数据平面 URI(包括版本),例如 https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931The SecretUri should be the full data-plane URI of a secret in Key Vault, including a version, e.g., https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931
VaultName=vaultName;SecretName=secretName;SecretVersion=secretVersionVaultName=vaultName;SecretName=secretName;SecretVersion=secretVersion VaultName 应该是 Key Vault 资源的名称。The VaultName should the name of your Key Vault resource. SecretName 应该是目标机密的名称。The SecretName should be the name of the target secret. SecretVersion 应该是要使用的机密的版本。The SecretVersion should be the version of the secret to use.

备注

当前需要版本。Versions are currently required. 轮换机密时,需在应用程序配置中更新版本。When rotating secrets, you will need to update the version in your application configuration.

例如,完整的引用将如下所示:For example, a complete reference would look like the following:

@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)

也可使用以下命令:Alternatively:

@Microsoft.KeyVault(VaultName=myvault;SecretName=mysecret;SecretVersion=ec96f02080254f109c51a1f14cdb1931)

Key Vault 中的源应用程序设置Source Application Settings from Key Vault

Key Vault 引用可以用作应用程序设置的值,以便将机密保存在 Key Vault 而不是站点配置中。可以对应用程序设置进行安全的静态加密,但如果需要机密管理功能,则应将它们置于 Key Vault 中。Key Vault references can be used as values for Application Settings, allowing you to keep secrets in Key Vault instead of the site config. Application Settings are securely encrypted at rest, but if you need secret management capabilities, they should go into Key Vault.

若要将 Key Vault 引用用于应用程序设置,请将引用设为设置的值。To use a Key Vault reference for an application setting, set the reference as the value of the setting. 应用可以通过密钥正常引用机密。Your app can reference the secret through its key as normal. 不需更改代码。No code changes are required.

提示

应该将大多数使用 Key Vault 引用的应用程序设置标记为槽设置,因为你应该为每个环境设置单独的保管库。Most application settings using Key Vault references should be marked as slot settings, as you should have separate vaults for each environment.

Azure 资源管理器部署Azure Resource Manager deployment

通过 Azure 资源管理器模板自动进行资源部署时,可能需要将依赖项按特定的顺序排列,这样才能使该功能发挥作用。When automating resource deployments through Azure Resource Manager templates, you may need to sequence your dependencies in a particular order to make this feature work. 请注意,需将应用程序设置定义为其自己的资源,而不能使用站点定义中的 siteConfig 属性。Of note, you will need to define your application settings as their own resource, rather than using a siteConfig property in the site definition. 这是因为,站点需先进行定义,这样才能使用它来创建系统分配标识并将该标识用在访问策略中。This is because the site needs to be defined first so that the system-assigned identity is created with it and can be used in the access policy.

函数应用的示例仿真模板可能如下所示:An example psuedo-template for a function app might look like the following:

{
    //...
    "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts",
            "name": "[variables('storageAccountName')]",
            //...
        },
        {
            "type": "Microsoft.Insights/components",
            "name": "[variables('appInsightsName')]",
            //...
        },
        {
            "type": "Microsoft.Web/sites",
            "name": "[variables('functionAppName')]",
            "identity": {
                "type": "SystemAssigned"
            },
            //...
            "resources": [
                {
                    "type": "config",
                    "name": "appsettings",
                    //...
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites', variables('functionAppName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/', variables('keyVaultName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', variables('keyVaultName'), variables('storageConnectionStringName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', variables('keyVaultName'), variables('appInsightsKeyName'))]"
                    ],
                    "properties": {
                        "AzureWebJobsStorage": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('storageConnectionStringResourceId')).secretUriWithVersion, ')')]",
                        "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('storageConnectionStringResourceId')).secretUriWithVersion, ')')]",
                        "APPINSIGHTS_INSTRUMENTATIONKEY": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('appInsightsKeyResourceId')).secretUriWithVersion, ')')]",
                        "WEBSITE_ENABLE_SYNC_UPDATE_SITE": "true"
                        //...
                    }
                },
                {
                    "type": "sourcecontrols",
                    "name": "web",
                    //...
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites', variables('functionAppName'))]",
                        "[resourceId('Microsoft.Web/sites/config', variables('functionAppName'), 'appsettings')]"
                    ],
                }
            ]
        },
        {
            "type": "Microsoft.KeyVault/vaults",
            "name": "[variables('keyVaultName')]",
            //...
            "dependsOn": [
                "[resourceId('Microsoft.Web/sites', variables('functionAppName'))]"
            ],
            "properties": {
                //...
                "accessPolicies": [
                    {
                        "tenantId": "[reference(concat('Microsoft.Web/sites/',  variables('functionAppName'), '/providers/Microsoft.ManagedIdentity/Identities/default'), '2015-08-31-PREVIEW').tenantId]",
                        "objectId": "[reference(concat('Microsoft.Web/sites/',  variables('functionAppName'), '/providers/Microsoft.ManagedIdentity/Identities/default'), '2015-08-31-PREVIEW').principalId]",
                        "permissions": {
                            "secrets": [ "get" ]
                        }
                    }
                ]
            },
            "resources": [
                {
                    "type": "secrets",
                    "name": "[variables('storageConnectionStringName')]",
                    //...
                    "dependsOn": [
                        "[resourceId('Microsoft.KeyVault/vaults/', variables('keyVaultName'))]",
                        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
                    ],
                    "properties": {
                        "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountResourceId'),'2015-05-01-preview').key1)]"
                    }
                },
                {
                    "type": "secrets",
                    "name": "[variables('appInsightsKeyName')]",
                    //...
                    "dependsOn": [
                        "[resourceId('Microsoft.KeyVault/vaults/', variables('keyVaultName'))]",
                        "[resourceId('Microsoft.Insights/components', variables('appInsightsName'))]"
                    ],
                    "properties": {
                        "value": "[reference(resourceId('microsoft.insights/components/', variables('appInsightsName')), '2015-05-01').InstrumentationKey]"
                    }
                }
            ]
        }
    ]
}

备注

在此示例中,源代码管理部署取决于应用程序设置。In this example, the source control deployment depends on the application settings. 这通常是不安全的行为,因为应用设置更新是以异步方式表现的。This is normally unsafe behavior, as the app setting update behaves asynchronously. 不过,由于我们已包括 WEBSITE_ENABLE_SYNC_UPDATE_SITE 应用程序设置,因此更新是同步的。However, because we have included the WEBSITE_ENABLE_SYNC_UPDATE_SITE application setting, the update is synchronous. 这意味着源代码管理部署只有在应用程序设置已完全更新后才会开始。This means that the source control deployment will only begin once the application settings have been fully updated.

Key Vault 引用疑难解答Troubleshooting Key Vault References

如果引用未正确解析,则将改用引用值。If a reference is not resolved properly, the reference value will be used instead. 这意味着,对于应用程序设置,将创建值具有 @no__t 的语法的环境变量。This means that for application settings, an environment variable would be created whose value has the @Microsoft.KeyVault(...) syntax. 这可能导致应用程序引发错误,因为它需要特定结构的机密。This may cause the application to throw errors, as it was expecting a secret of a certain structure.

最常见的原因是, Key Vault 访问策略的配置错误。Most commonly, this is due to a misconfiguration of the Key Vault access policy. 但是,这也可能是由于机密已不再存在,或者引用本身中存在语法错误。However, it could also be due to a secret no longer existing or a syntax error in the reference itself.

如果语法正确,可以通过在门户中检查当前解决方案状态来查看其他错误原因。If the syntax is correct, you can view other causes for error by checking the current resolution status in the portal. 导航到 "应用程序设置",然后选择 "编辑" 以获取相关引用。Navigate to Application Settings and select "Edit" for the reference in question. 在设置配置下面,应会看到状态信息,包括任何错误。Below the setting configuration, you should see status information, including any errors. 缺少这一点意味着引用语法无效。The absence of these implies that the reference syntax is invalid.

你还可以使用某个内置检测程序来获取其他信息。You can also use one of the built-in detectors to get additional information.

使用应用程序服务的检测程序Using the detector for App Service

  1. 在门户中,导航到你的应用。In the portal, navigate to your app.
  2. 选择 "诊断并解决问题"。Select Diagnose and solve problems.
  3. 选择 "可用性和性能",然后选择 " Web 应用"。Choose Availability and Performance and select Web app down.
  4. 查找Key Vault 应用程序设置诊断,并单击 "详细信息"。Find Key Vault Application Settings Diagnostics and click More info.

使用探测器进行 Azure FunctionsUsing the detector for Azure Functions

  1. 在门户中,导航到你的应用。In the portal, navigate to your app.
  2. 导航到 "平台功能"。Navigate to Platform features.
  3. 选择 "诊断并解决问题"。Select Diagnose and solve problems.
  4. 选择 "可用性和性能",然后选择 "函数应用关闭" 或 "报告错误"。Choose Availability and Performance and select Function app down or reporting errors.
  5. 单击 " Key Vault 应用程序设置" "诊断"。Click on Key Vault Application Settings Diagnostics.