Skip to content

Key vault access policy to RBAC migration – step by step

azure keyvault access policy to rbac how to

Introduction to Access Policies and RBAC

Migrating from Azure Key Vault Access Policies to Role-Based Access Control (RBAC) is a crucial step for modernizing your security configuration. With the general availability of Key Vault RBAC security configuration announced in 2021, Azure offers two ways to manage access to key vaults:

  • Azure Key Vault Access Policy (legacy since 2022)
  • Azure Key Vault RBAC (generally available since 2021)

Microsoft announced the deprecation of Azure Access Policies in 2022, prompting many organizations to transition to RBAC. This blog post provides a comprehensive guide on migrating from Azure Key Vault Access Policy to RBAC, including practical tips and challenges encountered during the process.

This article focuses on using Key Vault to manage secrets with managed identities for passwordless connections. The steps outlined here apply to other Key Vault functionalities as well, such as managing keys and encryption.

Differences between Access Policies and Role-Based Access Control (RBAC)

In managing permissions for Azure Key Vault, it’s crucial to understand the differences between RBAC (Role-Based Access Control) and access policies. Here’s a comparison to help you decide between using Azure Key Vault access policy vs RBAC, and to see the advantages of Azure Key Vault RBAC vs access policy.

FeatureAccess PoliciesRole-Based Access Control (RBAC)
AuthenticationAzureServiceTokenProviderDefaultAzureCredential
Access ControlDirectly defined on Key VaultManaged through Azure AD RBAC roles
Management ComplexityHigh (individual policies for each Key Vault)Lower (centralized role management)
LatencySlight overhead due to individual policy evaluationReduced latency with role caching
Setup and ConfigurationDirectly configure policies on Key VaultAssign roles via Azure AD at various scopes
IntegrationLimited integration with other Azure servicesSeamless integration with Azure AD and other Azure services

Why Migrate Key Vault to RBAC?

Microsoft considers access policies as legacy, and they are being phased out in favor of RBAC (Role-Based Access Control). Here are the main reasons to migrate to RBAC:

  • Enhanced Auditing and Monitoring: RBAC offers superior visibility and auditing capabilities. You can easily track and review role assignments and access through Azure Activity Logs and Azure Monitor.
  • Integration with PIM: RBAC integrates seamlessly with Privileged Identity Management (PIM), allowing for temporary, on-demand access rights. This integration enhances security and simplifies the management of privileged access.

Migrating to RBAC not only aligns with Microsoft’s current best practices but also enhances the security and manageability of your Azure environment.

Mapping Access Policies to RBAC Roles

Identify Access Needs

Start by identifying the access requirements and listing the current permissions granted via access policies. Every current access policy should be mapped to a corresponding RBAC role. Always enforce the Least Privilege Principle to ensure that users only have the permissions they need.

Conducting an In-depth Analysis

This analysis phase is crucial because switching to the Azure RBAC permission model invalidates all existing access policies. If equivalent Azure roles aren’t assigned, it can cause outages. Proper analysis ensures a smooth transition without disruptions.

Selecting Appropriate Built-In Roles

Azure provides several built-in roles to cover common access needs. Here are some key roles:

Built-in roleDescription
Key Vault AdministratorPerform all data plane operations on a key vault and all objects in it, including certificates, keys, and secrets
Key Vault readerRead metadata of key vaults and its certificates, keys, and secrets. Cannot read sensitive values such as secret contents or key material.
Key Vault Secres officerPerform any action on the secrets of a key vault, except manage permissions.
Key Vault Secrets UserRead secret contents including secret portion of a certificate with private key.

Creating Custom Roles

If the built-in roles do not meet your specific requirements, you may need to create custom roles. For a detailed comparison of access policy mapping to RBAC roles, refer to Microsoft’s documentation

Export access policies Using Azure CLI

Use the following Azure CLI script to export all access policies of a Key Vault:

az keyvault show --name <YourKeyVaultName> --query properties.accessPolicies

This script will help you gather and review the current access policies before transitioning to the RBAC model.

Client applications impact

Here’s a simple guide on how to authenticate to Azure Key Vault and access secrets using Azure.Identity and Role-Based Access Control (RBAC) in a .NET application.

Azure Access-Based Policy

To access secrets using Azure access policies, use the following code:

string keyVaultUrl = "https://<YourKeyVaultName>.vault.azure.net/";

var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

var secret = await keyVaultClient.GetSecretAsync(keyVaultUrl, "<YourSecretName>");
Console.WriteLine($"Secret value: {secret.Value}");

Azure RBAC access

For accessing secrets using Azure RBAC, use this code:

string keyVaultName = "<YourKeyVaultName>";
var kvUri = new Uri($"https://{keyVaultName}.vault.azure.net/");

var client = new SecretClient(vaultUri: kvUri, credential: new DefaultAzureCredential());
KeyVaultSecret secret = client.GetSecret("<YourSecretName>");

Authentication Details

The code snippet uses AzureServiceTokenProvider for authentication, which typically relies on managed identities or service principals.

For newer implementations, you might need to migrate from Microsoft.Azure.KeyVault to Azure.Security.KeyVault.Secrets. You can find a full tutorial and guidance document for this migration on GitHub.

Updating Infrastructure as Code (IAC) files

If you use any form of automated access management through IaC (Infrastructure as Code) or release pipelines, you need to update your code. Instead of assigning Key Vault access policies, you should now assign Key Vault RBAC (Role-Based Access Control) access rights.

Example of Bicep with Access policies:

param KeyvaultNamestring = 'kv-contoso'

resource keyVaultAccessPolicy 'Microsoft.KeyVault/vaults/accessPolicies@2022-07-01' = {
  name: any('${KeyvaultName}/add')
  properties: {
    accessPolicies: [
      {
        objectId: PrincipalId //user ID who's supposed to receive access
        tenantId: subscription().tenantId
        permissions: {
          secrets: [
            'get'
          ]
        }   
      }
    ]
  }
}

Example of bicep with RBAC:

resource keyVault 'Microsoft.KeyVault/vaults@2019-09-01' existing = {
  name: keyVaultName
}

@description('This is the built-in Key Vault Secret User role. See https://docs.microsoft.com/azure/role-based-access-control/built-in-roles#key-vault-secrets-user')
resource keyVaultSecretUserRoleRoleDefinition 'Microsoft.Authorization/roleDefinitions@2018-01-01-preview' existing = {
  scope: subscription()
  name: '4633458b-17de-408a-b874-0445c86b69e6'
}

@description('Grant the app service identity with key vault secret user role permissions over the key vault. This allows reading secret contents')
resource keyVaultSecretUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2020-08-01-preview' = {
  scope: keyVault
  name: guid(resourceGroup().id, appService.id, keyVaultSecretUserRoleRoleDefinition.id)
  properties: {
    roleDefinitionId: keyVaultSecretUserRoleRoleDefinition.id
    principalId: PrincipalId //user ID who's supposed to receive access
    principalType: 'ServicePrincipal'
  }
}

Migration Process & Strategy

When migrating to Azure Key Vault, it’s crucial to note that Key Vault doesn’t support both access policy and RBAC simultaneously. Therefore, a clear migration strategy is essential. Whether you choose a big bang or trickle migration approach, careful planning, thorough testing, and strong support are key to a smooth transition from access policies to RBAC.

Big Bang Migration vs Trickle migration

Big Bang Migration

Below image illustrates the steps involved to migrate keyvault using the big bang approach. We transition all access policies in one go.

Key Vault access policy migration big bang

Trickle Migration

Below image illustrates the steps involved to migrate keyvault using a trick approach. We transition gradually into small phases and test with every incremental change.

Key Vault access policy trickle migration

Comparison

Big Bang MigrationTrickle Migration
DescriptionTransitions all access policies to RBAC in one go.Gradually transitions access policies to RBAC in small phases.
Pros– Faster implementation.
– Simplifies the transition by avoiding dual systems.
– Reduced risk of disruptions.
– Easier to identify and fix issues.
Cons– Higher risk of access disruptions.
– Limited time for troubleshooting and adjustments.
– Takes longer to complete.
– Potential complexity in managing dual systems.

KeyVault-AccessPolicyToRBAC-CompareTool

This PowerShell project, maintained by Microsoft community members, is designed to compare Key Vault access policies with assigned RBAC roles. It helps ensure a smooth transition from the access policy to the RBAC permission model by verifying that all necessary roles and data actions are covered.

The tool provides two key files:

  • AccessPolicyRBACMapping.csv: This document maps the existing access policies to their corresponding RBAC roles.
  • CompareAccessPolicyToRBAC.ps1: This PowerShell script compares the assigned Key Vault access policies to RBAC roles, ensuring nothing is missed during the migration.

You can find this tool on GitHub: KeyVault-AccessPolicyToRBAC-CompareTool.

PowerShell tools for migration

While Microsoft doesn’t offer a one-click migration tool for Azure Key Vault, the community has created various scripts to help with the process.

This script extracts the access policies and assigns appropriate roles such as Key Vault Administrator, Key Vault Secrets Officer, Key Vault Secrets User, or Key Vault Reader based on the permissions (list/get/set/admin). For more details, refer to the documentation on Mapping Access Policies to RBAC Roles.

$keyvault = '<keyvaultnamehere>'
$resourceGroup = '<resourcegrouphere>'
$subscriptionId = '<subscriptionidhere>'

Function Set-Permission {
    param ($roleDef, $objectId)
    if ($null -eq $objectId -or $objectId -eq '') {
        Write-Host "Skipping due to empty ObjectId"
        return
    }
    $scope = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.KeyVault/vaults/$keyvault"

    if (-not (Get-AzRoleAssignment -Scope $scope -RoleDefinitionName $roleDef -ObjectId $objectId)) {
        Write-Host "Assigning role '$roleDef' to ObjectID '$objectId' on scope '$scope'"
        New-AzRoleAssignment -Scope $scope -RoleDefinitionName $roleDef -ObjectId $objectId
    } else {
        Write-Host "Role '$roleDef' for ObjectID '$objectId' on scope '$scope' already exists"
    }
}

(Get-AzKeyVault -VaultName $keyvault -ResourceGroupName $resourceGroup).AccessPolicies | ForEach-Object {
    $objId = $_.ObjectId
    Write-Host "Processing: $($_.DisplayName)"
    if ($_.DisplayName -contains "admin") {
        Set-Permission -roleDef "Key Vault Administrator" -objectId $objId
    } else {
        switch -wildcard ($_.PermissionsToSecretsStr) {
            "*set*" { Set-Permission -roleDef "Key Vault Secrets Officer" -objectId $objId; break }
            "*get*" { Set-Permission -roleDef "Key Vault Secrets User" -objectId $objId; break }
            "*list*" { Set-Permission -roleDef "Key Vault Reader" -objectId $objId }
        }
    }
}

#Switch key vault to RBAC mode
Update-AzKeyVault -VaultName $keyvault -ResourceGroupName $resourceGroup -EnableRbacAuthorization $true

Challenges and How to Overcome Them

Security Audit & Cleanup

Key Vault holds highly sensitive data, so it’s crucial to regularly audit and clean up access rights. Apply the principle of least privilege to ensure only necessary access is granted.

  • Access Review: Regularly review who has access to your Key Vault. Remove access for users who no longer need it, following the principle of least privilege.
  • Access Policies: Implement strict access policies to control who can read, write, or delete data. Use Azure Role-Based Access Control (RBAC) to manage permissions efficiently.

Insufficient User Access Rights

If users lack sufficient access to perform operations within Key Vault after migrating to RBAC, this issue is usually visible on the Azure dashboard. You can grant on-the-fly access or consider implementing Privileged Identity Management (PIM) to handle these sensitive access needs.

Applicative Problems

These are often the hardest to detect. Any application fetching Key Vault values in real time needs thorough testing. It’s better to define Key Vault connections in application settings since Azure provides status updates on these connections, allowing testing without executing the application layer. If applications with dynamic Key Vault connections fail, ensure the application code is updated.

Key Vault Insights (currently in preview) offers a useful overview of operations, helping to identify issues. For more information, see the Key Vault Insights Overview.

Preventing future creation of Access policy key vaults

After migrating all your key vaults to use RBAC, it’s important to stop users from creating or reverting key vaults to access policy mode. Azure makes this easy with a pre-defined policy: “Azure Key Vault should use RBAC permission model.”

This policy ensures that any new key vaults will follow the RBAC model, keeping your environment secure and consistent.

Keyvault policy defenition should use RBAC

Lessons Learned

While the migration from access policy to RBAC can be seen as a standalone task, it also presents an excellent opportunity to optimize several other aspects of your Azure environment. Use this migration to enforce the principle of least privilege, implement Privileged Identity Management (PIM), review application layer connections to Key Vault, and establish governance with Azure Policy.

Additionally, it’s crucial to regularly review RBAC assignments to ensure no undesired access is granted. Regular audits can help maintain a secure environment by identifying and removing unnecessary permissions.