使用 Key Vault 和 Azure PowerShell 管理存储帐户密钥Manage storage account keys with Key Vault and Azure PowerShell

Azure 存储帐户使用由帐户名和密钥构成的凭据。An Azure storage account uses credentials comprising an account name and a key. 密钥是自动生成的,充当密码而不是加密密钥。The key is autogenerated and serves as a password, rather than an as a cryptographic key. Key Vault 通过在存储帐户中定期重新生成存储帐户密钥来管理存储帐户密钥,并提供共享访问签名令牌,以便对存储帐户中的资源进行委托访问。Key Vault manages storage account keys by periodically regenerating them in storage account and provides shared access signature tokens for delegated access to resources in your storage account.

可以使用 Key Vault 托管的存储帐户密钥功能列出(同步) Azure 存储帐户中的密钥,并定期重新生成(轮换)密钥。You can use the Key Vault managed storage account key feature to list (sync) keys with an Azure storage account, and regenerate (rotate) the keys periodically. 可以管理存储帐户和经典存储帐户的密钥。You can manage keys for both storage accounts and Classic storage accounts.

使用托管的存储帐户密钥功能时,请注意以下要点:When you use the managed storage account key feature, consider the following points:

  • 响应调用方时永远不会返回密钥值。Key values are never returned in response to a caller.
  • 只有 Key Vault 能够管理存储帐户密钥。Only Key Vault should manage your storage account keys. 不要自行管理密钥,并避免干扰 Key Vault 进程。Don't manage the keys yourself and avoid interfering with Key Vault processes.
  • 只有单个 Key Vault 对象能够管理存储帐户密钥。Only a single Key Vault object should manage storage account keys. 不要允许从多个对象进行密钥管理。Don't allow key management from multiple objects.
  • 可以请求 Key Vault 使用用户主体(而不要使用服务主体)管理存储帐户。You can request Key Vault to manage your storage account with a user principal, but not with a service principal.
  • 只使用 Key Vault 重新生成密钥。Regenerate keys by using Key Vault only. 不要手动重新生成存储帐户密钥。Don't manually regenerate your storage account keys.

我们建议使用 Azure 存储与 Azure Active Directory (Azure AD) 的集成,这是 Microsoft 推出的基于云的标识和访问管理服务。We recommend using Azure Storage integration with Azure Active Directory (Azure AD), Microsoft's cloud-based identity and access management service. Azure AD 集成适用于 Azure Blob 和队列,提供对 Azure 存储的基于 OAuth2 令牌的访问(类似于 Azure Key Vault)。Azure AD integration is available for Azure blobs and queues, and provides OAuth2 token-based access to Azure Storage (just like Azure Key Vault).

Azure AD 允许使用应用程序标识或用户标识(而不是存储帐户凭据)对客户端应用程序进行身份验证。Azure AD allows you to authenticate your client application by using an application or user identity, instead of storage account credentials. 在 Azure 上运行时,可以使用 Azure AD 托管标识You can use an Azure AD managed identity when you run on Azure. 托管标识消除了客户端身份验证的需要,并可以在应用程序中存储凭据,或者将凭据与应用程序一同存储。Managed identities remove the need for client authentication and storing credentials in or with your application.

Azure AD 使用同样受 Key Vault 支持的基于角色的访问控制 (RBAC) 来管理授权。Azure AD uses role-based access control (RBAC) to manage authorization, which is also supported by Key Vault.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

服务主体应用程序 IDService principal application ID

Azure AD 租户为每个已注册的应用程序提供服务主体An Azure AD tenant provides each registered application with a service principal. 该服务主体充当应用程序 ID,通过 RBAC 设置访问其他 Azure 资源的授权期间,将使用它。The service principal serves as the application ID, which is used during authorization setup for access to other Azure resources via RBAC.

Key Vault 是已在所有 Azure AD 租户中预先注册的 Microsoft 应用程序。Key Vault is a Microsoft application that's pre-registered in all Azure AD tenants. Key Vault 注册到每个 Azure 云中的同一个应用程序 ID 下。Key Vault is registered under the same Application ID in each Azure cloud.

租户Tenants Cloud 应用程序 IDApplication ID
其他Other 任意Any cfa8b339-82a2-471a-a3c9-0fc0be7a4093

先决条件Prerequisites

若要完成本指南,必须先执行以下操作:To complete this guide, you must first do the following:

管理存储帐户密钥Manage storage account keys

连接到 Azure 帐户Connect to your Azure account

使用 Connect-AzAccount cmdlet 对 PowerShell 会话进行身份验证。Authenticate your PowerShell session using the Connect-AzAccount cmdlet.

Connect-AzAccount -EnvironmentName AzureChinaCloud

如果你有多个 Azure 订阅,可以使用 Get-AzSubscription cmdlet 列出这些订阅,并指定要与 Set-AzContext cmdlet 结合使用的订阅。If you have multiple Azure subscriptions, you can list them using the Get-AzSubscription cmdlet, and specify the subscription you wish to use with the Set-AzContext cmdlet.

Set-AzContext -SubscriptionId <subscriptionId>

设置变量Set variables

首先,通过以下步骤设置 PowerShell cmdlet 使用的变量。First, set the variables to be used by the PowerShell cmdlets in the following steps. 请务必更新 占位符,并将 $keyVaultSpAppId 设置为 cfa8b339-82a2-471a-a3c9-0fc0be7a4093(在上面的服务主体应用程序 ID 中指定)。Be sure to update the , , and placeholders, and set $keyVaultSpAppId to cfa8b339-82a2-471a-a3c9-0fc0be7a4093 (as specified in Service principal application ID, above).

我们还将使用 Azure PowerShell Get-AzContextGet-AzStorageAccount cmdlet 来获取你的用户 ID,以及 Azure 存储帐户的上下文。We will also use the Azure PowerShell Get-AzContext and Get-AzStorageAccount cmdlets to get your user ID and the context of your Azure storage account.

$resourceGroupName = <YourResourceGroupName>
$storageAccountName = <YourStorageAccountName>
$keyVaultName = <YourKeyVaultName>
$keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
$storageAccountKey = "key1" #(key1 or key2 are allowed)

# Get your User Id
$userId = (Get-AzContext).Account.Id

# Get a reference to your Azure storage account
$storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName

备注

对于经典存储帐户,请使用“primary”和“secondary”作为 $storageAccountKeyFor Classic Storage Account use "primary" and "secondary" for $storageAccountKey
对于经典存储帐户,请使用 'Get-AzResource -Name "ClassicStorageAccountName" -ResourceGroupName $resourceGroupName' 而不是 'Get-AzStorageAccount'Use 'Get-AzResource -Name "ClassicStorageAccountName" -ResourceGroupName $resourceGroupName' instead of'Get-AzStorageAccount' for Classic Storage Account

向 Key Vault 授予对你的存储帐户的访问权限Give Key Vault access to your storage account

只有在授权 Key Vault 访问你的存储帐户之后,它才可以访问和管理存储帐户密钥。Before Key Vault can access and manage your storage account keys, you must authorize its access your storage account. Key Vault 应用程序标识需要有权列出和重新生成存储帐户的密钥。The Key Vault application requires permissions to list and regenerate keys for your storage account. 可通过内置的 RBAC 角色存储帐户密钥操作员服务角色启用这些权限。These permissions are enabled through the built-in RBAC role Storage Account Key Operator Service Role.

使用 Azure PowerShell New-AzRoleAssignment cmdlet 将此角色分配到 Key Vault 服务主体,以将范围限定为你的存储帐户。Assign this role to the Key Vault service principal, limiting scope to your storage account, using the Azure PowerShell New-AzRoleAssignment cmdlet.

# Assign RBAC role "Storage Account Key Operator Service Role" to Key Vault, limiting the access scope to your storage account. For a classic storage account, use "Classic Storage Account Key Operator Service Role." 
New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id

成功完成角色分配后,应会看到类似于以下示例的输出:Upon successful role assignment, you should see output similar to the following example:

RoleAssignmentId   : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso/providers/Microsoft.Authorization/roleAssignments/189cblll-12fb-406e-8699-4eef8b2b9ecz
Scope              : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso
DisplayName        : Azure Key Vault
SignInName         :
RoleDefinitionName : storage account Key Operator Service Role
RoleDefinitionId   : 81a9662b-bebf-436f-a333-f67b29880f12
ObjectId           : 93c27d83-f79b-4cb2-8dd4-4aa716542e74
ObjectType         : ServicePrincipal
CanDelegate        : False

如果 Key Vault 已添加到存储帐户中的角色,则你会收到“角色分配已存在”If Key Vault has already been added to the role on your storage account, you'll receive a "The role assignment already exists." ”错误。error. 还可以使用 Azure 门户中存储帐户的“访问控制(IAM)”页验证角色分配。You can also verify the role assignment, using the storage account "Access control (IAM)" page in the Azure portal.

向托管存储帐户授予用户帐户权限Give your user account permission to managed storage accounts

使用 Azure PowerShell Set-AzKeyVaultAccessPolicy cmdlet 更新 Key Vault 访问策略,并向用户帐户授予存储帐户权限。Use the Azure PowerShell Set-AzKeyVaultAccessPolicy cmdlet to update the Key Vault access policy and grant storage account permissions to your user account.

# Give your user principal access to all storage account permissions, on your Key Vault instance

Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -UserPrincipalName $userId -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge

请注意,Azure 门户中存储帐户的“访问策略”页不会显示存储帐户的权限。Note that permissions for storage accounts aren't available on the storage account "Access policies" page in the Azure portal.

将托管存储帐户添加到 Key Vault 实例Add a managed storage account to your Key Vault instance

使用 Azure PowerShell Add-AzKeyVaultManagedStorageAccount cmdlet 在 Key Vault 实例中创建托管存储帐户。Use the Azure PowerShell Add-AzKeyVaultManagedStorageAccount cmdlet to create a managed storage account in your Key Vault instance. -DisableAutoRegenerateKey 开关指定不重新生成存储帐户密钥。The -DisableAutoRegenerateKey switch specifies NOT to regenerate the storage account keys.

# Add your storage account to your Key Vault's managed storage accounts

Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName $storageAccountKey -DisableAutoRegenerateKey

成功添加不重新生成密钥的存储帐户后,应会看到类似于以下示例的输出:Upon successful addition of the storage account with no key regeneration, you should see output similar to the following example:

Id                  : https://kvcontoso.vault.azure.cn:443/storage/sacontoso
Vault Name          : kvcontoso
AccountName         : sacontoso
Account Resource Id : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso
Active Key Name     : key1
Auto Regenerate Key : False
Regeneration Period : 90.00:00:00
Enabled             : True
Created             : 11/19/2018 11:54:47 PM
Updated             : 11/19/2018 11:54:47 PM
Tags                : 

启用密钥重新生成Enable key regeneration

如果希望 Key Vault 定期重新生成存储帐户密钥,可以使用 Azure PowerShell Add-AzKeyVaultManagedStorageAccount cmdlet 设置重新生成周期。If you want Key Vault to regenerate your storage account keys periodically, you can use the Azure PowerShell Add-AzKeyVaultManagedStorageAccount cmdlet to set a regeneration period. 此示例将重新生成周期设置为 3 天。In this example, we set a regeneration period of three days. 三天后,Key Vault 将重新生成“key2”,并将活动密钥从“key2”切换为“key1”(对于经典存储帐户,则替换为“primary”和“secondary”)。After three days, Key Vault will regenerate 'key2' and swap the active key from 'key2' to 'key1' (replace with 'primary' and 'secondary' for Classic Storage Accounts).

$regenPeriod = [System.Timespan]::FromDays(3)

Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName $storageAccountKey -RegenerationPeriod $regenPeriod

成功添加重新生成密钥的存储帐户后,应会看到类似于以下示例的输出:Upon successful addition of the storage account with key regeneration, you should see output similar to the following example:

Id                  : https://kvcontoso.vault.azure.cn:443/storage/sacontoso
Vault Name          : kvcontoso
AccountName         : sacontoso
Account Resource Id : /subscriptions/03f0blll-ce69-483a-a092-d06ea46dfb8z/resourceGroups/rgContoso/providers/Microsoft.Storage/storageAccounts/sacontoso
Active Key Name     : key1
Auto Regenerate Key : True
Regeneration Period : 3.00:00:00
Enabled             : True
Created             : 11/19/2018 11:54:47 PM
Updated             : 11/19/2018 11:54:47 PM
Tags                : 

共享访问签名令牌Shared access signature tokens

也可以要求 Key Vault 生成共享访问签名令牌。You can also ask Key Vault to generate shared access signature tokens. 共享访问签名对存储帐户中的资源提供委托访问。A shared access signature provides delegated access to resources in your storage account. 可以授予客户端访问存储帐户中的资源的权限,而无需共享帐户密钥。You can grant clients access to resources in your storage account without sharing your account keys. 使用共享访问签名可以安全共享存储资源,而不会透露帐户密钥。A shared access signature provides you with a secure way to share your storage resources without compromising your account keys.

本部分所述的命令将完成以下操作:The commands in this section complete the following actions:

  • 设置帐户共享访问签名定义。Set an account shared access signature definition.
  • 为 Blob、文件、表和队列服务创建帐户共享访问签名令牌。Create an account shared access signature token for Blob, File, Table, and Queue services. 为“服务”、“容器”和“对象”资源类型创建令牌。The token is created for resource types Service, Container, and Object. 创建的令牌拥有所有权限、通过 HTTPS 访问并指定了开始和结束日期。The token is created with all permissions, over https, and with the specified start and end dates.
  • 在保管库中设置 Key Vault 托管的存储共享访问签名定义。Set a Key Vault managed storage shared access signature definition in the vault. 该定义包含创建的共享访问签名令牌的模板 URI。The definition has the template URI of the shared access signature token that was created. 该定义使用共享访问签名类型 account,有效期为 N 天。The definition has the shared access signature type account and is valid for N days.
  • 验证共享访问签名是否已作为机密保存在 Key Vault 中。Verify that the shared access signature was saved in your key vault as a secret.

设置变量Set variables

首先,通过以下步骤设置 PowerShell cmdlet 使用的变量。First, set the variables to be used by the PowerShell cmdlets in the following steps. 请务必更新 占位符。Be sure to update the and placeholders.

我们还将使用 Azure PowerShell New-AzStorageContext cmdlet 来获取 Azure 存储帐户的上下文。We will also use the Azure PowerShell New-AzStorageContext cmdlets to get the context of your Azure storage account.

$storageAccountName = <YourStorageAccountName>
$keyVaultName = <YourKeyVaultName>

$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -Protocol Https -StorageAccountKey Key1 #(or "Primary" for Classic Storage Account)

创建共享访问签名令牌Create a shared access signature token

使用 Azure PowerShell New-AzStorageAccountSASToken cmdlet 创建共享访问签名定义。Create a shared access signature definition using the Azure PowerShell New-AzStorageAccountSASToken cmdlets.

$start = [System.DateTime]::Now.AddDays(-1)
$end = [System.DateTime]::Now.AddMonths(1)

$sasToken = New-AzStorageAccountSasToken -Service blob,file,Table,Queue -ResourceType Service,Container,Object -Permission "racwdlup" -Protocol HttpsOnly -StartTime $start -ExpiryTime $end -Context $storageContext

$sasToken 的值如下所示。The value of $sasToken will look similar to this.

?sv=2018-11-09&sig=5GWqHFkEOtM7W9alOgoXSCOJO%2B55qJr4J7tHQjCId9S%3D&spr=https&st=2019-09-18T18%3A25%3A00Z&se=2019-10-19T18%3A25%3A00Z&srt=sco&ss=bfqt&sp=racupwdl

生成共享访问签名定义Generate a shared access signature definition

使用 Azure PowerShell Set-AzKeyVaultManagedStorageSasDefinition cmdlet 创建共享访问签名定义。Use the the Azure PowerShell Set-AzKeyVaultManagedStorageSasDefinition cmdlet to create a shared access signature definition. 可将所选的名称提供给 -Name 参数。You can provide the name of your choice to the -Name parameter.

Set-AzKeyVaultManagedStorageSasDefinition -AccountName $storageAccountName -VaultName $keyVaultName -Name <YourSASDefinitionName> -TemplateUri $sasToken -SasType 'account' -ValidityPeriod ([System.Timespan]::FromDays(30))

验证共享访问签名定义Verify the shared access signature definition

可以使用 Azure PowerShell Get-AzKeyVaultSecret cmdlet 验证共享访问签名定义是否已存储在 Key Vault 中。You can verify that the shared access signature definition has been stored in your key vault using the Azure PowerShell Get-AzKeyVaultSecret cmdlet.

首先,在 Key Vault 中找到共享访问签名定义。First, find the shared access signature definition in your key vault.

Get-AzKeyVaultSecret -VaultName <YourKeyVaultName>

对应于 SAS 定义的机密包含以下属性:The secret corresponding to your SAS definition will have these properties:

Vault Name   : <YourKeyVaultName>
Name         : <SecretName>
...
Content Type : application/vnd.ms-sastoken-storage
Tags         :

现在,可以使用 Get-AzKeyVaultSecret cmdlet 和机密 Name 属性查看该机密的内容。You can now use the Get-AzKeyVaultSecret cmdlet and the secret Name property to view the content of that secret.

$secret = Get-AzKeyVaultSecret -VaultName <YourKeyVaultName> -Name <SecretName>

Write-Host $secret.SecretValueText

此命令的输出将显示 SAS 定义字符串。The output of this command will show your SAS definition string.

后续步骤Next steps