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?