azurepowershellazure-managed-identity

Access Token For User managed identity configuration


I PowerShell based scripts to update the configuration of azure resources , using Connect-AzAccount -Identity -AccountId $env:userid -WarningAction Ignore this way I am connecting the portal through user assigned managed identity , now I want create the access token to update the resources configuration by rest api method like invoking the uri. previously i had below method to create the access token $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -Headers @{Metadata="true"} this will give the token since it was system assigned managed identity it worked . how to create access token if we connect the portal through user assigned identity ?


Solution

  • To get access token using User assigned Managed Identity, you need to include either client_id or object_id in the PowerShell script.

    Initially, I created one user-assigned managed identity named usermid15 like this:

    enter image description here

    Make sure to add this managed identity to the Azure resource from which you want to generate access token. In my case, I added it to Azure Virtual Machine:

    enter image description here

    Now, I ran below PowerShell script in Azure VM and got access token successfully with user-assigned managed identity client ID:

    $clientId = "user_managed_client_Id"
    $response = Invoke-WebRequest -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F&client_id=$clientId" -Headers @{Metadata="true"}
    $accessToken = ($response.Content | ConvertFrom-Json).access_token
    Write-Output "Access Token: $accessToken"
    

    Response:

    enter image description here