Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Vault returns 401 with access token (MSI PowerShell Function App)

I am trying to connect to Keyvault with my Azure Function using PowerShell. The Managed Service Identity (MSI) has been turned on, and in Keyvault I granted the MSI 'get' and 'list' access policies. Using the script below I successfully get an access token, but when I make the request to Keyvault I always receive a 401 response.

$vaultName = $Env:KeyVaultName
$vaultSecretName = $Env:VaultSecretName

$tokenAuthURI = $Env:MSI_ENDPOINT + "?resource=https://vault.azure.net/&api-version=2017-09-01"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token

$headers = @{ 'Authorization' = "Bearer $accessToken" }
$queryUrl = "https://$vaultName.vault.azure.net/keys/" +$vaultSecretName + "?api-version=2016-10-01"

$keyResponse = Invoke-RestMethod -Method GET -Uri $queryUrl -Headers $headers

Any idea why the token is not sufficient?

like image 894
Swimburger Avatar asked Mar 15 '18 23:03

Swimburger


People also ask

How do I give Azure function to key vault?

Granting your app access to Key VaultCreate a managed identity for your application. Key Vault references will use the app's system assigned identity by default, but you can specify a user-assigned identity. Create an access policy in Key Vault for the application identity you created earlier.


1 Answers

Try changing the resource URI to https://vault.azure.net (with no trailing slash). The token validation on the server expects the exact same string as it returns in the 401 response's WWW-Authenticate header. In general, Key Vault returns 401 for cases where the token is missing or fails validation (three common cases are the token is expired, has an incorrect resource URI, or was issued by a different tenant than the vault is associated with).

like image 180
Sean Barnes Avatar answered Sep 19 '22 18:09

Sean Barnes