Skip to content

Manage Access Keys

Lab Objective

In this hands-on lab, you will learn how to:

  • Understand Azure Storage access keys and their role in authentication
  • Manage storage account access keys including rotation and regeneration
  • Test key rotation scenarios without service disruption
  • Implement secure key management practices for production environments
  • Configure applications to handle key rotation gracefully
  • Monitor and troubleshoot access key related issues

Scenario: Your organization has applications using storage account access keys for authentication. You need to implement a key rotation strategy to maintain security while ensuring zero downtime for production applications during key updates.


Pre-Provisioned Environment

The following Azure resources have been pre-deployed in your environment:

Resource Overview

Resource TypeResource NameConfigurationPurpose
Resource GroupAccessKeys-Lab-RGContains all lab resourcesLogical container
Storage Accountaccesskeyslab[unique]General Purpose v2Primary storage resource
Blob Containerapplication-dataPrivate access levelApplication file storage
Blob Containerbackup-dataPrivate access levelBackup file storage
App Servicewebapp-[unique]Web applicationSimulated production app
Function Appfuncapp-[unique]Serverless functionsBackground processing
Key Vaultkeyvault-[unique]Standard tierSecure key storage
Test VMTestVMWindows Server 2019Key rotation testing client

Application Architecture

Production Applications
β”œβ”€β”€ Web App (webapp-[unique])
β”‚ └── Uses Key1 for storage access
β”œβ”€β”€ Function App (funcapp-[unique])
β”‚ └── Uses Key2 for storage access
└── Test VM (TestVM)
└── Manual testing client
Storage Account (accesskeyslab[unique])
β”œβ”€β”€ Key1 (primary)
β”œβ”€β”€ Key2 (secondary)
└── Containers
β”œβ”€β”€ application-data
└── backup-data
Key Vault (keyvault-[unique])
└── Secure storage for rotated keys

VM Details

VMPrivate IPOperating SystemPurpose
TestVM10.0.1.4Windows Server 2019Test key rotation scenarios

Lab Exercises

Part 1: Examine Current Access Key Configuration

Step 1: Navigate to Storage Account Keys

  1. Navigate to AccessKeys-Lab-RG resource group
  2. Click on the Storage Account (accesskeyslab[unique])
  3. In the left menu, click Access keys
  4. Observe the two access keys:
    • Key1 (primary)
    • Key2 (secondary)

Step 2: Document Current Key Information

Record the following information:

  • Storage account name: accesskeyslab[unique]
  • Key1 name: Copy the key name
  • Key1 value: Copy the first few and last few characters (for identification)
  • Key2 name: Copy the key name
  • Key2 value: Copy the first few and last few characters (for identification)
  • Connection string: Copy both connection strings

Step 3: Test Current Key Access

  1. Click Show keys to reveal the key values
  2. Copy Key1 completely
  3. Open a new browser tab and go to Azure Storage Explorer online
  4. Test connection using Key1:
    • Select Storage account or service
    • Choose Account name and key
    • Enter storage account name and Key1
    • Verify: Should successfully connect and show containers

Part 2: Test Application Dependencies

Step 1: Check Web App Configuration

  1. Navigate to webapp-[unique]
  2. Click Configuration in the left menu
  3. Look for storage-related settings:
    • Find STORAGE_CONNECTION_STRING or similar
    • Note which key is being used (Key1 or Key2)
    • Do not modify at this stage

Step 2: Check Function App Configuration

  1. Navigate to funcapp-[unique]
  2. Click Configuration
  3. Examine application settings:
    • Look for AzureWebJobsStorage and other storage settings
    • Identify which key is configured
    • Record the configuration for later reference

Step 3: Connect to Test VM

  1. Navigate to TestVM
  2. Click Connect β†’ RDP
  3. Use credentials:
    • Username: azureuser
    • Password: LabPassword123!

Step 4: Test Storage Access from VM

From TestVM, open PowerShell and test both keys:

Terminal window
# Test Key1 access
$storageAccount = "accesskeyslab[unique]"
$key1 = "[KEY1-VALUE]"
$ctx1 = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $key1
try {
$containers = Get-AzStorageContainer -Context $ctx1
Write-Host "Key1 Test: SUCCESS - Found $($containers.Count) containers"
$containers | ForEach-Object { Write-Host " - $($_.Name)" }
} catch {
Write-Host "Key1 Test: FAILED - $($_.Exception.Message)"
}
# Test Key2 access
$key2 = "[KEY2-VALUE]"
$ctx2 = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $key2
try {
$containers = Get-AzStorageContainer -Context $ctx2
Write-Host "Key2 Test: SUCCESS - Found $($containers.Count) containers"
} catch {
Write-Host "Key2 Test: FAILED - $($_.Exception.Message)"
}

Expected Result: Both keys should work and return the same container list


Part 3: Implement Zero-Downtime Key Rotation

Step 1: Identify Current Key Usage

Before rotating, document which applications use which keys:

ApplicationCurrent KeyConfiguration Location
Web AppKey1 or Key2Application Settings
Function AppKey1 or Key2Application Settings
Manual ScriptsBothVarious locations

Step 2: Plan Rotation Strategy

Zero-downtime rotation process:

  1. Identify the unused key (if web app uses Key1, then Key2 is free to rotate)
  2. Regenerate the unused key
  3. Update applications to use the newly regenerated key
  4. Test new key functionality
  5. Regenerate the old key (now unused)

Step 3: Regenerate Key2 (Assuming it’s unused)

  1. In Storage Account Access keys
  2. Click regenerate for Key2 (three dots menu β†’ Regenerate)
  3. Confirm regeneration in the dialog
  4. Copy the new Key2 value

Step 4: Test New Key2

From TestVM PowerShell:

Terminal window
# Test newly regenerated Key2
$newKey2 = "[NEW-KEY2-VALUE]"
$ctxNew = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $newKey2
try {
$containers = Get-AzStorageContainer -Context $ctxNew
Write-Host "New Key2 Test: SUCCESS - Regenerated key works"
# Test file operations
$testContent = "Test content - " + (Get-Date)
$blob = Set-AzStorageBlobContent -Context $ctxNew -Container "application-data" -File "C:\temp\test.txt" -Blob "key-rotation-test.txt" -Force
Write-Host "New Key2 Write Test: SUCCESS - Can write files"
} catch {
Write-Host "New Key2 Test: FAILED - $($_.Exception.Message)"
}

Part 4: Update Application Configurations

Step 1: Update Web App to Use New Key2

  1. Navigate to webapp-[unique]
  2. Click Configuration
  3. Find the storage connection string setting
  4. Update the key value in the connection string:
    • Change from old Key2 to new Key2
    • Or switch from Key1 to new Key2
  5. Save the configuration
  6. Restart the web app to apply changes

Step 2: Update Function App Configuration

  1. Navigate to funcapp-[unique]
  2. Click Configuration
  3. Update storage-related settings:
    • AzureWebJobsStorage: Update to use new Key2
    • Other storage settings: Update as needed
  4. Save configuration
  5. Restart function app

Step 3: Test Applications After Update

Test Web App:

  1. Browse to the web app URL
  2. Verify: Application loads and functions normally
  3. Check logs for any storage-related errors

Test Function App:

  1. Trigger a function (if possible)
  2. Monitor execution in the portal
  3. Check logs for successful storage operations

Part 5: Complete the Key Rotation

Step 1: Verify All Applications Use New Key

Confirm applications are working with the new key before proceeding:

From TestVM, test the old key to confirm it’s no longer needed:

Terminal window
# Test if old Key1 is still being used somewhere
$oldKey1 = "[OLD-KEY1-VALUE]"
$ctxOld = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $oldKey1
# This should still work since we haven't regenerated Key1 yet
try {
Get-AzStorageContainer -Context $ctxOld | Out-Null
Write-Host "Old Key1: Still valid (not yet regenerated)"
} catch {
Write-Host "Old Key1: No longer valid"
}

Step 2: Regenerate Key1

  1. In Storage Account Access keys
  2. Regenerate Key1 (the previously used key)
  3. Confirm regeneration
  4. Copy the new Key1 value

Step 3: Test Complete Rotation

From TestVM PowerShell:

Terminal window
# Test the newly regenerated Key1
$newKey1 = "[NEW-KEY1-VALUE]"
$ctxNewKey1 = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $newKey1
try {
$containers = Get-AzStorageContainer -Context $ctxNewKey1
Write-Host "New Key1 Test: SUCCESS - Both keys have been rotated"
} catch {
Write-Host "New Key1 Test: FAILED - $($_.Exception.Message)"
}
# Verify old keys no longer work
try {
$ctxOldKey1 = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $oldKey1
Get-AzStorageContainer -Context $ctxOldKey1 | Out-Null
Write-Host "Security Issue: Old Key1 still works!"
} catch {
Write-Host "Security Confirmed: Old Key1 properly invalidated"
}

Part 6: Secure Key Storage with Key Vault

Step 1: Store Keys in Key Vault

  1. Navigate to keyvault-[unique]
  2. Click Secrets in the left menu
  3. Add new secrets:

Secret 1:

  • Name: storage-key1
  • Value: New Key1 value
  • Content type: application/x-storage-key

Secret 2:

  • Name: storage-key2
  • Value: New Key2 value
  • Content type: application/x-storage-key
  1. Set appropriate expiration dates (e.g., 90 days for rotation reminder)

Step 2: Configure Applications to Use Key Vault

Update Web App configuration:

  1. Navigate to webapp-[unique] β†’ Configuration
  2. Add Key Vault reference:
    • Name: STORAGE_KEY
    • Value: @Microsoft.KeyVault(SecretUri=https://keyvault-[unique].vault.azure.net/secrets/storage-key2/)
  3. Update connection string to reference the Key Vault secret

Step 3: Test Key Vault Integration

From TestVM PowerShell:

Terminal window
# Test Key Vault secret retrieval (requires authentication setup)
$keyVaultName = "keyvault-[unique]"
$secretName = "storage-key1"
# This would typically be done with managed identity in production
try {
$secret = Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $secretName -AsPlainText
Write-Host "Key Vault Test: SUCCESS - Retrieved key from vault"
# Test storage access with Key Vault key
$ctxVault = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $secret
$containers = Get-AzStorageContainer -Context $ctxVault
Write-Host "Key Vault Storage Test: SUCCESS - Key works for storage access"
} catch {
Write-Host "Key Vault Test: Authentication required - $($_.Exception.Message)"
}

Part 7: Monitor and Automate Key Rotation

Step 1: Set Up Monitoring Alerts

  1. Navigate to Storage Account β†’ Monitoring β†’ Alerts
  2. Create alert rule for key usage:
    • Signal: Transactions
    • Condition: When authentication failures > threshold
    • Action: Email notification

Step 2: Document Key Rotation Schedule

Create rotation schedule:

KeyCurrent Rotation DateNext Rotation DueResponsible Team
Key1[Today’s date][90 days from now]Security Team
Key2[Today’s date][90 days from now]DevOps Team

Step 3: Create Rotation Checklist

Key rotation procedure:

  1. Identify unused key (Key1 or Key2)
  2. Regenerate unused key
  3. Update Key Vault with new key value
  4. Test applications using Key Vault reference
  5. Monitor for errors for 24 hours
  6. Regenerate the other key
  7. Update documentation and schedule next rotation

Troubleshooting Guide

Common Access Key Issues

IssueSymptomsPossible CauseSolution
Application authentication failures403 Forbidden errorsKey regenerated but app not updatedUpdate application configuration
Intermittent connection issuesSome operations failMixed key usage during rotationEnsure all connections use same key
Key Vault access deniedCannot retrieve secretsMissing permissionsConfigure managed identity or access policies
Applications won’t startStartup failuresInvalid connection stringVerify connection string format
Storage Explorer connection failsCannot connectWrong key or account nameVerify account name and key values

Key Rotation Validation

CheckMethodExpected Result
New key functionalityTest storage operationsAll operations succeed
Old key invalidationTest with old keyAuthentication failure
Application healthMonitor app logsNo authentication errors
Key Vault integrationRetrieve secretsSuccessful secret access

Additional Experiments

Try these optional exercises to deepen your understanding:

  • Automated Key Rotation: Use Azure Functions to automate key rotation
  • Managed Identity: Replace access keys with managed identity authentication
  • Key Rotation Scripts: Create PowerShell scripts for automated rotation
  • Multi-Region Scenarios: Test key rotation across geo-replicated storage
  • Disaster Recovery: Practice key recovery scenarios

Key Takeaways

After completing this lab, you should understand:

  • Azure Storage provides two access keys for zero-downtime rotation scenarios
  • Key rotation requires careful planning to avoid service disruption
  • Applications should be updated before regenerating currently used keys
  • Key Vault integration provides centralized and secure key management
  • Monitoring and alerting are essential for detecting key-related issues
  • Regular key rotation is a security best practice for production environments
  • Managed identities are preferred over access keys when possible

Access Key Management Best Practices

Security Practices

  • Rotate keys regularly (every 90 days recommended)
  • Use Key Vault for centralized key storage
  • Implement monitoring for authentication failures
  • Document rotation procedures and assign responsibilities
  • Test rotation process in non-production environments first

Operational Practices

  • Use one key for applications, keep one for rotation
  • Update applications before regenerating active keys
  • Monitor applications after key updates
  • Maintain rotation schedules and documentation
  • Consider managed identities as alternative to access keys

Access Keys vs Managed Identity

Comparison Table

FeatureAccess KeysManaged Identity
SecurityRequires key managementNo credential management
RotationManual process requiredAutomatic rotation
ComplexitySimple initial setupRequires RBAC configuration
Audit TrailLimited trackingFull Azure AD audit logs
ScopeFull storage account accessGranular RBAC permissions

Migration Path

  1. Identify applications using access keys
  2. Enable managed identity for Azure resources
  3. Configure RBAC permissions for storage access
  4. Update application code to use managed identity
  5. Test functionality thoroughly
  6. Disable access key usage once migration complete

Additional Resources