Managing Key Vault with a Service Principal

Today's blog post comes from Jason Fritts, a support engineer on the Azure Identity Support Team in Microsoft CSS.

 I was recently working with a customer who was trying to automate some Key Vault management tasks such as updating a Key Vault's access policy but was running into access errors like this one:


The customer was authenticating to Azure via service principal clientID\clientSecret like the following:
             

$clientid = "<service principal client id">

$password = ConvertTo-SecureString "<service principal client secret>" -AsPlainText -Force

$psCred = New-Object System.Management.Automation.PSCredential($clientId, $password)

Login-AzureRMAccount -Credential $pscred -ServicePrincipal -TenantID <Tenant ID>

 

 We verified that the customer had already granted management plane (RBAC) access for this service principal to the Key Vault. We also verified that the customer had granted data plane (Key Vault access policy) permissions to this service principal.

 
After troubleshooting, it was determined that the permissions required were related to Graph calls made to Azure Active Directory which require at least read access.  By default, a user principal has the necessary permissions to make Graph calls to its own Azure Active Directory tenant, but service principals do not.  In order to grant a service principal the permissions to perform directory read operations, you can add the service principal to the Azure Active Directory "Directory Readers" built-in role with the following:

 

$sp = Get-AzureADServicePrincipal -ObjectId <object ID of service principal>

Add-AzureADDirectoryRoleMember -ObjectId (Get-AzureADDirectoryRole | where-object {$_.DisplayName -eq "Directory Readers"}).Objectid -RefObjectId $sp.ObjectId

NOTE: This process can only be performed in PowerShell currently with the Azure AD PowerShell module, you can not add service principals to AAD roles via the portal today.

Reference: https://docs.microsoft.com/en-us/powershell/azure/active-directory/signing-in-service-principal?view=azureadps-2.0#give-the-service-principal-reader-access-to-the-current-tenant-get-azureaddirectoryrole

After granting the service principal the required permissions, you can now run operations such as Set-AzureRmKeyVaultAccessPolicy with service principal credentials.

Thank you Jason!

I hope this helps you out when using the Azure Key Vault!  Please follow us on Twitter and tweet about it!
@WinDevMatt @AzIdentity

Add comment