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

自动轮换使用两组身份验证凭据的资源的机密Automate the rotation of a secret for resources that have two sets of authentication credentials

向 Azure 服务进行身份验证的最佳方法是使用托管标识,但某些情况下无法做到这一点。The best way to authenticate to Azure services is by using a managed identity, but there are some scenarios where that isn't an option. 在此类情况下,将使用访问密钥或密码。In those cases, access keys or passwords are used. 应经常轮换访问密钥和密码。You should rotate access keys and passwords frequently.

本教程介绍如何定期自动轮换使用两组身份验证凭据的数据库和服务的机密。This tutorial shows how to automate the periodic rotation of secrets for databases and services that use two sets of authentication credentials. 具体而言,本教程演示了如何将 Azure Key Vault 中存储的 Azure 存储帐户密钥作为机密进行轮换。Specifically, this tutorial shows how to rotate Azure Storage account keys stored in Azure Key Vault as secrets. 你将使用由 Azure 事件网格通知触发的函数。You'll use a function triggered by Azure Event Grid notification.

备注

如果为委托的存储帐户访问提供共享访问签名令牌,则可在 Key Vault 中自动管理存储帐户密钥。Storage account keys can be automatically managed in Key Vault if you provide shared access signature tokens for delegated access to the storage account. 有些服务需要具有访问密钥的存储帐户连接字符串。There are services that require storage account connection strings with access keys. 对于这种情况,建议采用此解决方案。For that scenario, we recommend this solution.

下面是本教程中介绍的轮换解决方案:Here's the rotation solution described in this tutorial:

显示轮换解决方案的关系图。

在此解决方案中,Azure Key Vault 将存储帐户的单个访问密钥存储为同一机密的不同版本,在后续版本中作为主密钥和辅助密钥交替使用。In this solution, Azure Key Vault stores storage account individual access keys as versions of the same secret, alternating between the primary and secondary key in subsequent versions. 当一个访问密钥存储到最新版本的机密中时,将重新生成备用密钥并将其作为最新版本的机密添加到 Key Vault 中。When one access key is stored in the latest version of the secret, the alternate key is regenerated and added to Key Vault as the new latest version of the secret. 该解决方案提供了应用程序的完整轮换周期,以便刷新到重新生成的最新密钥。The solution provides the application's entire rotation cycle to refresh to the newest regenerated key.

  1. 在机密过期之前的 30 天,Key Vault 会向事件网格发布“即将过期”事件。Thirty days before the expiration date of a secret, Key Vault publishes the near expiry event to Event Grid.
  2. 事件网格会检查事件订阅,并使用 HTTP POST 调用已订阅该事件的函数应用终结点。Event Grid checks the event subscriptions and uses HTTP POST to call the function app endpoint that's subscribed to the event.
  3. 函数应用会标识备用密钥(而不是最新密钥),并调用存储帐户来重新生成该密钥。The function app identifies the alternate key (not the latest one) and calls the storage account to regenerate it.
  4. 函数应用将重新生成的新密钥添加到 Azure Key Vault 中,作为机密的新版本。The function app adds the new regenerated key to Azure Key Vault as the new version of the secret.

先决条件Prerequisites

  • Azure 订阅。An Azure subscription. 免费创建一个。Create one for free.
  • Azure Cloud ShellAzure Cloud Shell. 本教程将门户 Cloud Shell 与 PowerShell 环境结合使用This tutorial is using portal Cloud Shell with PowerShell env
  • Azure Key Vault。Azure Key Vault.
  • 两个 Azure 存储帐户。Two Azure storage accounts.

如果当前没有密钥保管库和存储帐户,可使用此部署链接:You can use this deployment link if you don't have an existing key vault and existing storage accounts:

标记为“部署到 Azure”的链接。Link that's labelled Deploy to Azure.

  1. 在“资源组”下,选择“新建”。Under Resource group, select Create new. 将组命名为“vaultrotation”,然后选择“确定” 。Name the group vaultrotation and then select OK.

  2. 选择“查看 + 创建”。Select Review + create.

  3. 选择“创建” 。Select Create.

    显示如何创建资源组的屏幕截图。

现在,你拥有一个密钥保管库和两个存储帐户。You'll now have a key vault and two storage accounts. 可运行以下命令,在 Azure CLI 中验证此设置:You can verify this setup in the Azure CLI by running this command:

az resource list -o table -g vaultrotation

结果类似于以下输出:The result will look something like this output:

Name                     ResourceGroup         Location    Type                               Status
-----------------------  --------------------  ----------  ---------------------------------  --------
vaultrotation-kv         vaultrotation      westus      Microsoft.KeyVault/vaults
vaultrotationstorage     vaultrotation      westus      Microsoft.Storage/storageAccounts
vaultrotationstorage2    vaultrotation      westus      Microsoft.Storage/storageAccounts

创建和部署密钥轮换函数Create and deploy the key rotation function

接下来,你将创建一个使用系统托管标识的函数应用,以及其他必需组件。Next, you'll create a function app with a system-managed identity, in addition to other required components. 还将为存储帐户密钥部署轮换函数。You'll also deploy the rotation function for the storage account keys.

函数应用轮换函数需要以下组件和配置:The function app rotation function requires the following components and configuration:

  • 一个 Azure 应用服务计划An Azure App Service plan
  • 一个用于管理函数应用触发器的存储帐户A storage account to manage function app triggers
  • 用于访问 Key Vault 中的机密的访问策略An access policy to access secrets in Key Vault
  • 向函数应用分配的存储帐户密钥操作员服务角色,分配目的是使其可可访问存储帐户访问密钥The Storage Account Key Operator Service role assigned to the function app so it can access storage account access keys
  • 一个具有事件触发器和 HTTP 触发器的密钥轮换函数(按需轮换)A key rotation function with an event trigger and an HTTP trigger (on-demand rotation)
  • SecretNearExpiry 事件的事件网格事件订阅An Event Grid event subscription for the SecretNearExpiry event
  1. 选择 Azure 模板部署链接:Select the Azure template deployment link:

    Azure 模板部署链接。Azure template deployment link.

  2. 在“资源组”列表中选择“vaultrotation” 。In the Resource group list, select vaultrotation.

  3. 在“存储帐户 RG”框中,输入存储帐户所在的资源组的名称。In the Storage Account RG box, enter the name of the resource group in which your storage account is located. 如果要部署密钥轮换函数的资源组中已存在你的存储帐户,请保留默认值 [resourceGroup().name]。Keep the default value [resourceGroup().name] if your storage account is already located in the same resource group where you'll deploy the key rotation function.

  4. 在“存储帐户名称”框中,输入包含要轮换的访问密钥的存储帐户名称。In the Storage Account Name box, enter the name of the storage account that contains the access keys to rotate. 如果你使用在先决条件中创建的存储帐户,请保留默认值 [concat(resourceGroup().name, 'storage')]。Keep the default value [concat(resourceGroup().name, 'storage')] if you use storage account created in Prerequisites.

  5. 在“Key Vault RG”框中,输入密钥保管库所在的资源组的名称。In the Key Vault RG box, enter the name of resource group in which your key vault is located. 如果要部署密钥轮换函数的资源组中已存在你的密钥保管库,请保留默认值 [resourceGroup().name]。Keep the default value [resourceGroup().name] if your key vault already exists in the same resource group where you'll deploy the key rotation function.

  6. 在“密钥保管库名称”框中,输入密钥保管库的名称。In the Key Vault Name box, enter the name of the key vault. 如果你使用在先决条件中创建的存储帐户,请保留默认值 [concat(resourceGroup().name, '-kv')]。Keep the default value [concat(resourceGroup().name, '-kv')] if you use key vault created in Prerequisites.

  7. 在“应用服务计划类型”框中,选择“托管计划”。In the App Service Plan Type box, select hosting plan. 仅当密钥保管库位于防火墙之后时才需要“高级计划”。Premium Plan is needed only when your key vault is behind firewall.

  8. 在“函数应用名称”框中,输入函数应用的名称。In the Function App Name box, enter the name of the function app.

  9. 在“机密名称”框中,输入要在其中存储访问密钥的机密的名称。In the Secret Name box, enter the name of the secret where you'll store access keys.

  10. 在“存储库 URL”框中,输入函数代码的 GitHub 位置。In the Repo URL box, enter the GitHub location of the function code. 在本教程中,你可以使用 https://github.com/Azure-Samples/KeyVault-Rotation-StorageAccountKey-PowerShell.git。In this tutorial you can use https://github.com/Azure-Samples/KeyVault-Rotation-StorageAccountKey-PowerShell.git .

  11. 选择“查看 + 创建”。Select Review + create.

  12. 选择“创建” 。Select Create.

    演示如何创建和部署函数的屏幕截图。

完成上述步骤后,你将获得一个存储帐户、一个服务器场、一个函数应用和 Application Insights。After you complete the preceding steps, you'll have a storage account, a server farm, a function app, and Application Insights. 部署完成后,你将看到以下页面:When the deployment is complete, you'll see this page:

显示“部署已完成”页的屏幕截图。

备注

如果遭遇失败,可选择“重新部署”来完成组件的部署。If you encounter a failure, you can select Redeploy to finish the deployment of the components.

可以在 Azure 示例中找到轮换函数的部署模板和代码。You can find deployment templates and code for the rotation function in Azure Samples.

将存储帐户访问密钥添加到 Key VaultAdd the storage account access keys to Key Vault

首先,设置访问策略,以向用户主体授予“管理机密”权限:First, set your access policy to grant manage secrets permissions to your user principal:

az keyvault set-policy --upn <email-address-of-user> --name vaultrotation-kv --secret-permissions set delete get list

现在,可使用存储帐户访问密钥作为值来创建新的机密。You can now create a new secret with a storage account access key as its value. 要使轮换函数可在存储帐户中重新生成密钥,还需要提供要添加到机密的存储帐户资源 ID、机密有效期和密钥 ID。You'll also need the storage account resource ID, secret validity period, and key ID to add to the secret so the rotation function can regenerate the key in the storage account.

确定存储帐户资源 ID。Determine the storage account resource ID. 可在 id 属性中找到该值。You can find this value in the id property.

az storage account show -n vaultrotationstorage

列出存储帐户访问密钥,以便可获取密钥值:List the storage account access keys so you can get the key values:

az storage account keys list -n vaultrotationstorage 

将机密和存储帐户资源 ID 添加到过期日期设置为明天、有效期为 60 天的密钥保管库。使用检索到的 key1ValuestorageAccountResourceId 的值运行此命令:Add secret to key vault with expiration date set to tomorrow, validity period for 60 days and storage account resource id. Run this command, using your retrieved values for key1Value and storageAccountResourceId:

$tomorrowDate = (get-date).AddDays(+1).ToString("yyy-MM-ddTHH:mm:ssZ")
az keyvault secret set --name storageKey --vault-name vaultrotation-kv --value <key1Value> --tags "CredentialId=key1" "ProviderAddress=<storageAccountResourceId>" "ValidityPeriodDays=60" --expires $tomorrowDate

上述机密会在几分钟内触发 SecretNearExpiry 事件。Above secret will trigger SecretNearExpiry event within several minutes. 此事件转而将触发函数来轮换过期时间设置为 60 天的机密。This event will in turn trigger the function to rotate the secret with expiration set to 60 days. 在该配置中,“SecretNearExpiry”事件将每 30 天(过期前 30 天)触发一次,并且轮换函数将在 key1 与 key2 之间交替轮换。In that configuration, 'SecretNearExpiry' event would be triggered every 30 days (30 days before expiry) and rotation function would will alternate rotation between key1 and key2.

可检索存储帐户密钥和 Key Vault 机密并对其进行比较,从而验证是否重新生成了访问密钥。You can verify that access keys have regenerated by retrieving the storage account key and the Key Vault secret and compare them.

使用此命令获取机密信息:Use this command to get the secret information:

az keyvault secret show --vault-name vaultrotation-kv --name storageKey

请注意,CredentialId 已更新为备用 keyName,并且 value 已重新生成:Notice that CredentialId is updated to the alternate keyName and that value is regenerated:

显示第一个存储帐户的 a z keyvault secret show 命令输出的屏幕截图。

检索访问密钥以比较值:Retrieve the access keys to compare the values:

az storage account keys list -n vaultrotationstorage 

请注意,密钥的 value 与密钥保管库中的机密相同:Notice that value of the key is same as secret in key vault:

显示第一个存储帐户的 a z storage account keys list 命令输出的屏幕截图。

添加存储帐户以进行轮换Add storage accounts for rotation

可重复使用同一个函数应用来为多个存储帐户轮换密钥。You can reuse the same function app to rotate keys for multiple storage accounts.

若要将存储帐户密钥添加到现有函数以进行轮换,你需要:To add storage account keys to an existing function for rotation, you need:

  • 向函数应用分配的存储帐户密钥操作员服务角色,分配目的是使它可访问存储帐户访问密钥。The Storage Account Key Operator Service role assigned to function app so it can access storage account access keys.
  • SecretNearExpiry 事件的事件网格事件订阅。An Event Grid event subscription for the SecretNearExpiry event.
  1. 选择 Azure 模板部署链接:Select the Azure template deployment link:

    Azure 模板部署链接。Azure template deployment link.

  2. 在“资源组”列表中选择“vaultrotation” 。In the Resource group list, select vaultrotation.

  3. 在“存储帐户 RG”框中,输入存储帐户所在的资源组的名称。In the Storage Account RG box, enter the name of the resource group in which your storage account is located. 如果要部署密钥轮换函数的资源组中已存在你的存储帐户,请保留默认值 [resourceGroup().name]。Keep the default value [resourceGroup().name] if your storage account is already located in the same resource group where you'll deploy the key rotation function.

  4. 在“存储帐户名称”框中,输入包含要轮换的访问密钥的存储帐户名称。In the Storage Account Name box, enter the name of the storage account that contains the access keys to rotate.

  5. 在“Key Vault RG”框中,输入密钥保管库所在的资源组的名称。In the Key Vault RG box, enter the name of resource group in which your key vault is located. 如果要部署密钥轮换函数的资源组中已存在你的密钥保管库,请保留默认值 [resourceGroup().name]。Keep the default value [resourceGroup().name] if your key vault already exists in the same resource group where you'll deploy the key rotation function.

  6. 在“密钥保管库名称”框中,输入密钥保管库的名称。In the Key Vault Name box, enter the name of the key vault.

  7. 在“函数应用名称”框中,输入函数应用的名称。In the Function App Name box, enter the name of the function app.

  8. 在“机密名称”框中,输入要在其中存储访问密钥的机密的名称。In the Secret Name box, enter the name of the secret where you'll store access keys.

  9. 选择“查看 + 创建”。Select Review + create.

  10. 选择“创建” 。Select Create.

    显示如何创建其他存储帐户的屏幕截图。

将其他存储帐户访问密钥添加到 Key VaultAdd another storage account access key to Key Vault

确定存储帐户资源 ID。Determine the storage account resource ID. 可在 id 属性中找到该值。You can find this value in the id property.

az storage account show -n vaultrotationstorage2

列出存储帐户访问密钥,以便可获取密钥 2 值:List the storage account access keys so you can get the key2 value:

az storage account keys list -n vaultrotationstorage2 

将机密和存储帐户资源 ID 添加到过期日期设置为明天、有效期为 60 天的密钥保管库。使用检索到的 key2ValuestorageAccountResourceId 的值运行此命令:Add secret to key vault with expiration date set to tomorrow, validity period for 60 days and storage account resource id. Run this command, using your retrieved values for key2Value and storageAccountResourceId:

$tomorrowDate = (get-date).AddDays(+1).ToString("yyy-MM-ddTHH:mm:ssZ")
az keyvault secret set --name storageKey2 --vault-name vaultrotation-kv --value <key2Value> --tags "CredentialId=key2" "ProviderAddress=<storageAccountResourceId>" "ValidityPeriodDays=60" --expires $tomorrowDate

使用此命令获取机密信息:Use this command to get the secret information:

az keyvault secret show --vault-name vaultrotation-kv --name storageKey2

请注意,CredentialId 已更新为备用 keyName,并且 value 已重新生成:Notice that CredentialId is updated to the alternate keyName and that value is regenerated:

显示第二个存储帐户的 a z keyvault secret show 命令输出的屏幕截图。

检索访问密钥以比较值:Retrieve the access keys to compare the values:

az storage account keys list -n vaultrotationstorage 

请注意,密钥的 value 与密钥保管库中的机密相同:Notice that value of the key is same as secret in key vault:

显示第二个存储帐户的 a z storage account keys list 命令输出的屏幕截图。

两组凭据的 Key Vault 轮换函数Key Vault rotation functions for two sets of credentials

两组凭据和几个现成函数的轮换函数模板:Rotation functions template for two sets of credentials and several ready to use functions:

备注

上述轮换函数由社区成员(而不是 Microsoft)创建。Above rotation functions are created by a member of the community and not by Microsoft. 任何 Microsoft 支持计划或服务都不支持社区 Azure 函数,这些函数按原样提供,无任何形式的保证。Community Azure Functions are not supported under any Microsoft support programme or service, and are made available AS IS without warranty of any kind.

后续步骤Next steps