允许应用访问 Azure Stack Hub Key Vault 机密Allow apps to access Azure Stack Hub Key Vault secrets

本文中的步骤说明如何运行示例应用 HelloKeyVault,该应用从 Azure Stack Hub 中的密钥保管库检索密钥和机密。The steps in this article describe how to run the sample app HelloKeyVault that retrieves keys and secrets from a key vault in Azure Stack Hub.

先决条件Prerequisites

如果已通过 VPN 建立连接,可以从 Azure Stack 开发工具包或从基于 Windows 的外部客户端安装以下必备组件:You can install the following prerequisites from the Azure Stack Development Kit, or from a Windows-based external client if you're connected through VPN:

创建密钥保管库并注册应用Create a key vault and register an app

若要准备示例应用程序,请执行以下操作:To prepare for the sample application:

  • 在 Azure Stack Hub 中创建密钥保管库。Create a key vault in Azure Stack Hub.
  • 在 Azure Active Directory (Azure AD) 中注册应用。Register an app in Azure Active Directory (Azure AD).

使用 Azure 门户或 PowerShell 来准备示例应用。Use the Azure portal or PowerShell to prepare for the sample app.

备注

默认情况下,此 PowerShell 脚本会在 Active Directory 中创建一个新的应用。By default, the PowerShell script creates a new app in Active Directory. 不过,你也可以注册现有的某个应用程序。However, you can register one of your existing applications.

在运行以下脚本之前,请确保为 aadTenantNameapplicationPassword 变量提供值。Before running the following script, make sure you provide values for the aadTenantName and applicationPassword variables. 如果没有为 applicationPassword 指定值,此脚本会生成随机密码。If you don't specify a value for applicationPassword, this script generates a random password.

$vaultName           = 'myVault'
$resourceGroupName   = 'myResourceGroup'
$applicationName     = 'myApp'
$location            = 'local'

# Password for the application. If not specified, this script generates a random password during app creation.
$applicationPassword = ''

# Function to generate a random password for the application.
Function GenerateSymmetricKey()
{
    $key = New-Object byte[](32)
    $rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
    $rng.GetBytes($key)
    return [System.Convert]::ToBase64String($key)
}

Write-Host 'Please log into your Azure Stack Hub user environment' -foregroundcolor Green

$tenantARM = "https://management.local.azurestack.external"
$aadTenantName = "FILL THIS IN WITH YOUR AAD TENANT NAME. FOR EXAMPLE: myazurestack.partner.onmschina.cn"

# Configure the Azure Stack Hub operator's PowerShell environment.
Add-AzureRMEnvironment `
  -Name "AzureStackUser" `
  -ArmEndpoint $tenantARM

$TenantID = Get-AzsDirectoryTenantId `
  -AADTenantName $aadTenantName `
  -EnvironmentName AzureStackUser

# Sign in to the user portal.
Add-AzureRmAccount `
  -EnvironmentName "AzureStackUser" `
  -TenantId $TenantID `

$now = [System.DateTime]::Now
$oneYearFromNow = $now.AddYears(1)

$applicationPassword = GenerateSymmetricKey

# Create a new Azure AD application.
$identifierUri = [string]::Format("http://localhost:8080/{0}",[Guid]::NewGuid().ToString("N"))
$homePage = "https://contoso.com"

Write-Host "Creating a new AAD Application"
$ADApp = New-AzureRmADApplication `
  -DisplayName $applicationName `
  -HomePage $homePage `
  -IdentifierUris $identifierUri `
  -StartDate $now `
  -EndDate $oneYearFromNow `
  -Password $applicationPassword

Write-Host "Creating a new AAD service principal"
$servicePrincipal = New-AzureRmADServicePrincipal `
  -ApplicationId $ADApp.ApplicationId

# Create a new resource group and a key vault in that resource group.
New-AzureRmResourceGroup `
  -Name $resourceGroupName `
  -Location $location

Write-Host "Creating vault $vaultName"
$vault = New-AzureRmKeyVault -VaultName $vaultName `
  -ResourceGroupName $resourceGroupName `
  -Sku standard `
  -Location $location

# Specify full privileges to the vault for the application.
Write-Host "Setting access policy"
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName `
  -ObjectId $servicePrincipal.Id `
  -PermissionsToKeys all `
  -PermissionsToSecrets all

Write-Host "Paste the following settings into the app.config file for the HelloKeyVault project:"
'<add key="VaultUrl" value="' + $vault.VaultUri + '"/>'
'<add key="AuthClientId" value="' + $servicePrincipal.ApplicationId + '"/>'
'<add key="AuthClientSecret" value="' + $applicationPassword + '"/>'
Write-Host

下图显示用于创建密钥保管库的脚本的输出:The following image shows the output from the script used to create the key vault:

具有访问密钥的密钥保管库

请记下前面脚本返回的 VaultUrlAuthClientIdAuthClientSecret 值。Make a note of the VaultUrl, AuthClientId, and AuthClientSecret values returned by the previous script. 将使用这些值运行 HelloKeyVault 应用程序。You use these values to run the HelloKeyVault application.

下载并配置示例应用程序Download and configure the sample application

从 Azure 密钥保管库客户端示例页下载密钥保管库示例。Download the key vault sample from the Azure Key Vault client samples page. 将 .zip 文件的内容解压缩到开发工作站上。Extract the contents of the .zip file on your development workstation. samples 文件夹中有两个应用,本文使用了 HelloKeyVault。There are two apps in the samples folder; this article uses HelloKeyVault.

若要加载 HelloKeyVault 示例,请执行以下操作:To load the HelloKeyVault sample:

  1. 浏览到 Microsoft.Azure.KeyVault.Samples > samples > HelloKeyVault 文件夹。Browse to the Microsoft.Azure.KeyVault.Samples > samples > HelloKeyVault folder.
  2. 在 Visual Studio 中打开 HelloKeyVault 应用。Open the HelloKeyVault app in Visual Studio.

配置示例应用程序Configure the sample application

在 Visual Studio 中:In Visual Studio:

  1. 打开 HelloKeyVault\App.config 文件,找到 <appSettings> 元素。Open the HelloKeyVault\App.config file and find the <appSettings> element.

  2. 使用创建密钥保管库时返回的值更新 VaultUrlAuthClientIdAuthCertThumbprint 密钥。Update the VaultUrl, AuthClientId, and AuthCertThumbprint keys with the values returned when creating the key vault. 默认情况下,App.config 文件有一个用于 AuthCertThumbprint 的占位符。By default, the App.config file has a placeholder for AuthCertThumbprint. 请将此占位符替换为 AuthClientSecretReplace this placeholder with AuthClientSecret.

    <appSettings>
     <!-- Update these settings for your test environment -->
     <add key="VaultUrl" value="URL to your Vault" />
     <add key="AuthClientId" value="Client Id of your Service Principal" />
     <add key="AuthCertThumbprint" value="Thumbprint of the certificate used for authentication" />
     <add key="TracingEnabled" value="false" />
    </appSettings>
    
  3. 重新生成解决方案。Rebuild the solution.

运行应用程序Run the app

运行 HelloKeyVault 时,应用会登录到 Azure AD,然后使用 AuthClientSecret 令牌向 Azure Stack Hub 中的密钥保管库进行身份验证。When you run HelloKeyVault, the app signs in to Azure AD and then uses the AuthClientSecret token to authenticate to the key vault in Azure Stack Hub.

可以使用 HelloKeyVault 示例执行以下操作:You can use the HelloKeyVault sample to:

  • 对密钥和机密执行基本操作,例如创建、加密、包装和删除。Perform basic operations such as create, encrypt, wrap, and delete on the keys and secrets.
  • HelloKeyVault 传递诸如 encryptdecrypt 之类的参数,以及向密钥保管库应用指定的更改。Pass parameters such as encrypt and decrypt to HelloKeyVault, and apply the specified changes to a key vault.

后续步骤Next steps