Invoke-WebRequest to get access token for system assigned identity

sakuraime 2,321 Reputation points

On an Azure VM , I have assigned a system managed identity, and I would like to get that from powershell on that machine .

However I got the following error


I want to use it to authen to Azure sql database

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
7,409 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. shiva patpi 13,161 Reputation points Microsoft Employee

    Hello @sakuraime ,
    Thanks for your query. I was able to repro your issue locally but with different error message:
    Initially for the below command in the client_id parameter, I was trying to pass the ObjectID instead of ApplicationID

    PS C:\windows\system32> $response = Invoke-WebRequest -Uri '' -Method GET -Headers @{Metadata="true"}

    Invoke-WebRequest : {"error":"invalid_request","error_description":"Identity not found"}
    At line:1 char:13

    • $response = Invoke-WebRequest -Uri ' ...
    • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    • FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

    This will be the complete working command:

    PS C:\windows\system32> $response = Invoke-WebRequest -Uri '' -Method GET -Headers @{Metadata="true"}
    PS C:\windows\system32> $response

    StatusCode : 200
    StatusDescription : OK
    Content : {"access_token":"TOKENVALU}
    RawContent : HTTP/1.1 200 OK
    Content-Length: 1715
    Content-Type: application/json; charset=utf-8
    Date: Fri, 26 Feb 2021 18:49:16 GMT
    Server: IMDS/150.870.65.489

    Forms : {}
    Headers : {[Content-Length, 1715], [Content-Type, application/json; charset=utf-8], [Date, Fri, 26 Feb 2021 18:49:16 GMT], [Server, IMDS/150.870.65.489]}
    Images : {}
    InputFields : {}
    Links : {}
    ParsedHtml : System.__ComObject
    RawContentLength : 1715

    How to get the applicationID:

    1) Get-AzureRmADServicePrincipal -DisplayName "managedidentity"
    Above command will display the list of all IDs.
    2) Get the ObjectID of the VM from Azure Portal ( VMName - > Settings -> Identity ) -
    3) From the output , search for that ObjectID copied from portal
    4) Grab the ApplicationID
    5) Try to run the whole command in one single line

    Pass that applicationID to the Invoke-WebRequest command . It should work

    My Azure VM machine Screen Shots of Successful and Unsuccessful attempts:


    Below Additional references should help you out in troubleshooting further:

    If the above information helps , Kindly "Accept the Answer and Upvote"