7

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?

Swimburger
  • 6,681
  • 6
  • 36
  • 63
  • 1
    If you want to get secret, you need to use queryUrl `"https://$vaultName.vault.azure.net/secrets/" +$vaultSecretName + "?api-version=2016-10-01"`. In your case, it seems that you try to get the key. Do you granted the MSI 'get' and 'list' access policies to access key? – Tom Sun - MSFT Mar 16 '18 at 01:20
  • @TomSun thank you for noticing I wrongly put `keys` in there. Once Sean helped me get passed the 401, the error messages guided me there too :) – Swimburger Mar 16 '18 at 01:26

1 Answers1

10

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).

Sean Barnes
  • 316
  • 2
  • 4