401 Unauthorised while retrieving keys from Key vault in API

276 Views Asked by At

I want to know keys present in Azure Key Vault using API. Referred this document: (https://learn.microsoft.com/en-us/rest/api/keyvault/keys/get-keys/get-keys?tabs=HTTP) Using this request to get bearer token in my PC:-

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=client_credentials&client_id=3aaf24aa-a918-442f-9973-7c056d3a79ae&client_secret=xxxx&scope=https%3A%2F%2Fmanagement.azure.com%2F.default' https://login.microsoftonline.com/811f967e-0856-4e36-92e3-60224639e39d/oauth2/v2.0/token

But calling API failing with 401 unauthorized message: { "error": { "code": "Unauthorized", "message": "AKV10022: Invalid audience. Expected https://vault.azure.net, found: https://management.azure.com." } }

Anyone faced similar issue and get success in listing keys from key vault using API.

PS: I can get the keys in CLI and Powershell but I want same from API

CLI - az keyvault key list --vault-name mykeyvault

Powershell - Get-AzKeyVaultKey -VaultName 'mykeyvault'

1

There are 1 best solutions below

0
On BEST ANSWER

The error occurred as you are using wrong scope to generate the access token. To resolve the error, change scope to https://vault.azure.net/.default

In my case, I registered one Azure AD application and added API permission as below:

enter image description here

Make sure to grant proper RBAC role like Key Vault Administrator to the service principal under your key vault like this:

enter image description here

Now, I generated access token using below curl command by replacing scope:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'grant_type=client_credentials&client_id=appId&client_secret=secret&scope=https%3A%2F%2Fvault.azure.net%2F.default' https://login.microsoftonline.com/tenant/oauth2/v2.0/token

Response:

enter image description here

When I used this token to call API via Postman, I got list of keys successfully in response as below:

GET https://srikv23.vault.azure.net//keys?&api-version=7.4

Response:

enter image description here