January 27, 2021

Azure Managed Identity: Obtaining token gives error ‘invalid_client’

Problem

One of our Azure App Services suddenly started behaving badly and throwing HTTP 400 errors. From Application Insights we could see the error was coming from a call to LOCALHOST:PORT/MSI/token which is the location where access token is requested in case your code wants to access other Azure resources using Managed Identity (formerly MSI).

Troubleshooting

I went to Kudu PowerShell console of the given App Service and tried to manually get the access_token, but couldn’t.

Command for that is:
Invoke-WebRequest -Uri 'http://127.0.0.1:41332/MSI/token/?resource=https://management.azure.com/&api-version=2017-09-01' -Method GET -Headers @{Metadata="true";Secret="$env:MSI_SECRET"} -UseBasicParsing

Note! Port in the URL is different in your App Service, you can get it via @env:MSI_ENDPOINT.

All I got was HTTP 401 error with ‘invalid_client’ error code. Strange. In respective DEV App Service there was no errors and access_code was returned nicely.

By the way, details of the Uri and other parameters can be found here. Header is different if you’re using more recent api-version.

By the way, if you just run the Invoke-WebRequest, you will get error:

Win32 internal error "The handle is invalid" 0x6 occurred while reading the console output buffer. Contact Microsoft Customer Support Services.

No point in contacting MS Support, just run the following command and retry:

$ProgressPreference="SilentlyContinue"

Solution

Now, for the solution…good old IISRESET. Of course in Azure you restart the App Service in question. After restarting the App Service, you can re-run the Invoke-WebRequest, and access_token is returned correctly, and App Service works.

No comments:

Post a Comment