Permitir que aplicativos acedam a segredos do Azure Stack Hub Key VaultAllow apps to access Azure Stack Hub Key Vault secrets

Os passos deste artigo descrevem como executar a aplicação de amostra HelloKeyVault que recupera chaves e segredos de um cofre chave em 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.

Pré-requisitosPrerequisites

Pode instalar os seguintes pré-requisitos a partir do Kit de Desenvolvimento da Pilha Azure,ou a partir de um cliente externo baseado no Windows se estiver conectado através da VPN: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:

Crie um cofre chave e registe uma aplicaçãoCreate a key vault and register an app

Para preparar a aplicação da amostra:To prepare for the sample application:

  • Crie um cofre chave no Azure Stack Hub.Create a key vault in Azure Stack Hub.
  • Registe uma aplicação no Azure Ative Directory (Azure AD).Register an app in Azure Active Directory (Azure AD).

Utilize o portal Azure ou o PowerShell para preparar a aplicação da amostra.Use the Azure portal or PowerShell to prepare for the sample app.

Nota

Por padrão, o script PowerShell cria uma nova aplicação no Ative Directory.By default, the PowerShell script creates a new app in Active Directory. No entanto, pode registar uma das suas aplicações existentes.However, you can register one of your existing applications.

Antes de executar o seguinte script, certifique-se de fornecer valores para as aadTenantName applicationPassword variáveis e variáveis.Before running the following script, make sure you provide values for the aadTenantName and applicationPassword variables. Se não especificar um valor para applicationPassword , este script gera uma senha aleatória.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.onmicrosoft.com"

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

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

# Sign in to the user portal.
Add-AzAccount `
  -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-AzADApplication `
  -DisplayName $applicationName `
  -HomePage $homePage `
  -IdentifierUris $identifierUri `
  -StartDate $now `
  -EndDate $oneYearFromNow `
  -Password $applicationPassword

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

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

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

# Specify full privileges to the vault for the application.
Write-Host "Setting access policy"
Set-AzKeyVaultAccessPolicy -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

A imagem a seguir mostra a saída do script utilizado para criar o cofre de chaves:The following image shows the output from the script used to create the key vault:

Cofre de chaves com chaves de acesso

Tome nota dos valores VaultUrl, AuthClientId e AuthClientSecret devolvidos pelo script anterior.Make a note of the VaultUrl, AuthClientId, and AuthClientSecret values returned by the previous script. Utiliza estes valores para executar a aplicação HelloKeyVault.You use these values to run the HelloKeyVault application.

Descarregue e configuure a aplicação da amostraDownload and configure the sample application

Descarregue a amostra do cofre chave da página de amostras do cliente do Azure Key Vault.Download the key vault sample from the Azure Key Vault client samples page. Extraia o conteúdo do ficheiro .zip na sua estação de trabalho de desenvolvimento.Extract the contents of the .zip file on your development workstation. Existem duas aplicações na pasta das amostras; este artigo utiliza HelloKeyVault.There are two apps in the samples folder; this article uses HelloKeyVault.

Para carregar a amostra HelloKeyVault:To load the HelloKeyVault sample:

  1. Navegue na pasta Microsoft.Azure.KeyVault.Samples > samples > HelloKeyVault.Browse to the Microsoft.Azure.KeyVault.Samples > samples > HelloKeyVault folder.
  2. Abra a aplicação HelloKeyVault no Visual Studio.Open the HelloKeyVault app in Visual Studio.

Configurar o exemplo de aplicaçãoConfigure the sample application

No Estúdio Visual:In Visual Studio:

  1. Abra o ficheiro HelloKeyVault\App.config e encontre o <appSettings> elemento.Open the HelloKeyVault\App.config file and find the <appSettings> element.

  2. Atualize as teclas VaultUrl, AuthClientId e AuthCertThumbprint com os valores devolvidos ao criar o cofre de chaves.Update the VaultUrl, AuthClientId, and AuthCertThumbprint keys with the values returned when creating the key vault. Por predefinição, o ficheiro App.config tem um espaço reservado para AuthCertThumbprint .By default, the App.config file has a placeholder for AuthCertThumbprint. Substitua este espaço reservado por AuthClientSecret .Replace 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. Reconstruir a solução.Rebuild the solution.

Executar a aplicaçãoRun the app

Quando executar HelloKeyVault, a aplicação entra no Azure AD e, em seguida, usa o AuthClientSecret token para autenticar no cofre chave no 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.

Pode utilizar a amostra HelloKeyVault para:You can use the HelloKeyVault sample to:

  • Execute operações básicas como criar, encriptar, embrulhar e apagar as chaves e segredos.Perform basic operations such as create, encrypt, wrap, and delete on the keys and secrets.
  • Passe parâmetros como encrypt e decrypt para HelloKeyVault, e aplique as alterações especificadas num cofre de chaves.Pass parameters such as encrypt and decrypt to HelloKeyVault, and apply the specified changes to a key vault.

Passos seguintesNext steps