Unlocking Azure Secrets: Using Identities for Key Vault Access
Published Oct 02 2023 11:28 AM 15.7K Views
Microsoft

Azure Key Vault is essential for securely managing keys, secrets, and certificates. Managed Identities (MI) allow Azure resources to authenticate to any service that supports Azure AD authentication without any credentials in your code.  For those looking to swiftly test Managed Identities for Azure Key Vault access from a Virtual Machine, this blog provides step-by-step implementation details. We will delve into both User Assigned Managed Identity (UAMI) and System Assigned Managed Identity (SAMI), helping you determine the best approach for your needs.

 

Prerequisites

For more on Key Vault with Managed Identities, check this link out.

 

When to Use UAMI vs. SAMI

 

User Assigned Managed Identity (UAMI):

  • Flexibility: Use UAMI when you need the flexibility to associate one identity with multiple Azure resources, or multiple identities with a single resource.
  • Longevity: UAMIs are not tied to the lifecycle of the resource they're associated with. Even if the resource is deleted, the UAMI remains.
  • Specific Use Cases: Ideal for scenarios where you need fine-grained control, like when certain VMs should have different permissions than others, even within the same resource group.

System Assigned Managed Identity (SAMI):

  • Simplicity: SAMI is tied directly to the Azure resource's lifecycle, making it easier to manage. When the resource is deleted, the SAMI is automatically removed.
  • Automatic: Ideal for scenarios where an identity should exist only as long as the associated Azure resource exists.
  • Broad Use Cases: Best for general use cases where each resource can have its own unique identity.

 

Using User Assigned Managed Identity (UAMI) to Read Key Vault Secrets

 

1. Create Identity

# First, define the UAMI and the resource group:

 

$vmname='winvm-new'
$uamiName = "UID1"
$resourceGroup = "rg01"
$subscriptionID = "<sub-id>"
$keyVaultName = "kv01"

 

Then, create the UAMI:

 

New-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $uamiName

 

 

2. Assign Identity to VM

 

# Bind the created UAMI to a VM:
$vm = Get-AzVM -ResourceGroupName $resourceGroup -Name $vmname
Update-AzVM -ResourceGroupName $resourceGroup -VM $vm -IdentityType "UserAssigned" `
   -IdentityID "/subscriptions/$subscriptionID/resourcegroups/$resourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$uamiName"

 

 

3. Retrieve UAMI Principal ID

 

# Fetch the principal ID for the UAMI:
$uami = az identity show --name $uamiName --resource-group $resourceGroup `
   --query principalId --output tsv
echo $uami

 

 

4. Grant Key Vault Permissions for UAMI

 

# Assign necessary permissions to access the Key Vault secrets:
az keyvault set-policy --name $keyVaultName --object-id $uami `
    --secret-permissions get list --key-permissions get list

# Ensure the permissions are correctly set:
az keyvault show --name $keyVaultName --query "properties.accessPolicies"

 

# Key Vault portal view should display the following:varghesejoji_0-1696267105785.png

 

5. Acquire Access Token for UAMI

 

# Fetch an access token using the UAMIs Client ID:
$clientID = az identity show --name $uamiName `
    --resource-group $resourceGroup --query clientId --output tsv

$baseUri = 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net&client_id='

$uri = $baseUri + $clientID
echo $uri

# Invoke GET to query the Azure Instance Metadata Service (IMDS) to obtain the access token:
$Response = Invoke-RestMethod -Uri $uri -Method GET -Headers @{Metadata="true"}

$KeyVaultToken = $Response.access_token
echo $KeyVaultToken

 

 

6. Retrieve Secret from Key Vault

 

# Finally, use the acquired token to fetch secrets from the Key Vault:
$secretName = 'secret1'
$apiVersion = "2016-10-01"
$baseUri = "https://$keyVaultName.vault.azure.net/secrets/"

$uri = $baseUri + $secretName + "?api-version=" + $apiVersion

Invoke-RestMethod -Uri $uri `
   -Method GET -Headers @{Authorization="Bearer $KeyVaultToken"}

 

 

 

Using System Assigned Managed Identity (SAMI) to Read Key Vault Secrets

 

1. Enable SAMI on VM

 

#Activate the system-assigned managed identity for your Azure VM
$vmname='winvm-new'
$resourceGroup = "rg01"
$keyVaultName = "kv01"

$vm = Get-AzVM -ResourceGroupName $resourceGroup -Name $vmname

Update-AzVM -ResourceGroupName $resourceGroup -VM $vm `
   -IdentityType SystemAssigned

 

 

2. Retrieve SAMI Principal ID

 

#Get the principal ID for SAMI:
$identity = az vm identity show --name $vmname `
   --resource-group $resourceGroup --query principalId `
   --output json | ConvertFrom-Json

echo $identity

 

 

3. Grant the "Key Vault Reader" Role to SAMI

 

#Assign the required permissions:
$keyVaultId = (az keyvault show --name $keyVaultName --query id --output tsv)

az role assignment create --assignee $identity --role "Key Vault Reader" `
   --scope $keyVaultId

 

 

4. Create Access policy for SAMI

 

# Assign necessary permissions to access the Key Vault secrets:
az keyvault set-policy --name $keyVaultName --object-id $identity `
   --secret-permissions get list --key-permissions get list

# Ensure the permissions are correctly set:
az keyvault show --name $keyVaultName --query "properties.accessPolicies"

 

# Key Vault portal view should display the following, showing the VM named applicationvarghesejoji_1-1696267105787.png

 

5. Acquire Access Token for SAMI

 

#For SAMI, you don’t need a client ID:
$Response = Invoke-RestMethod -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://vault.azure.net' -Method GET -Headers @{Metadata="true"}

$KeyVaultToken = $Response.access_token
echo $KeyVaultToken

 

 

6. Retrieve Secret from Key Vault with SAMI

 

#Fetch the secret:
$baseUri = "https://$keyVaultName.vault.azure.net/secrets/"
$uri = $baseUri + $secretName + "?api-version=" + $apiVersion

Invoke-RestMethod -Uri $uri -Method GET `
   -Headers @{Authorization="Bearer $KeyVaultToken"}

 

 

Conclusion

With the detailed steps provided in this guide, one can swiftly set up and verify Managed Identities for accessing Azure Key Vault from a VM. Whether using UAMI or SAMI, this hands-on approach offers a quick and tangible way to validate your setup, ensuring that your Azure resources are not only functional but also securely configured. By following these instructions, you're taking a proactive step towards robust security practices, seamlessly integrating, and verifying your Managed Identities with Azure Key Vault.

 

Disclaimer

The sample scripts are not supported by any Microsoft standard support program or service. The sample scripts are provided AS IS without a warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.

Co-Authors
Version history
Last update:
‎Oct 02 2023 10:15 PM
Updated by: