Share via

acquire a token of app registration with MI , via powershell Rest in an azure function app

Guy Levi 5 Reputation points Microsoft Employee
2025-05-20T11:28:46.15+00:00

Hello,

I am trying to acquire a token from an app registration. Since this app registration has API permissions I want to use, I need to do it with managed identity.

To achieve this, I created a function app where I published the following code.
the client is the App registration client id ( should it be something else ?)

Also not sure if the scope is the correct way to write it .

param($Request, $TriggerMetadata)

# Set the client ID of the App Registration that the managed identity is federated to
$clientId = "3f13273c-3fab-4887-94ec-e9c29b543dc1"

# Set the scope for the token (usually the App ID URI of the target API)
$scope = "api://AzureADTokenExchange/.default"

# Request the token from Azure Instance Metadata Service (IMDS)
try {
    $response = Invoke-RestMethod -Method GET -Headers @{Metadata="true"} -Uri "http://169.254.169.254/metadata/identity/oauth2/token?client_id=$clientId&resource=$scope&api-version=2018-02-01"
    
    # Extract the token
    $accessToken = $response

    # Return the token in the HTTP response
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = 200
        Body = @{
            access_token = $accessToken
        } | ConvertTo-Json -Depth 3
    })
} catch {
    # Handle error and return the error response
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = 500
        Body = @("Error retrieving token: $($_.Exception.Message)")
    })
}

As you can see in the attached screen shot it is being published properly.

I also have a federated identity based on the managed identity I created on the app registration, and that same identity is in the Azure function.

However, when I try to get the response to see if it has the token, the response is constantly empty. I believe there is an issue with how I am trying to acquire the token with the invoke request , in the code.

# Define the function URL

az account set --subscription "51828c2e-c358-414d-9739-e799a65b0fdf"


$functionKey = az functionapp function keys list --name R2D-Kusto-AzureFunctionPs --resource-group kusto-r2d-resources --function-name gettokenfunction --query "default" --output tsv | Out-String


$functionKey = $functionKey.Trim()

$functionUrl = "https://r2d-kusto-azurefunctionps.azurewebsites.net/api/gettokenfunction?code=$functionKey"

# Call the function
$response = Invoke-RestMethod -Uri $functionUrl -Method GET

# Extract and display the token
$token = $response
Write-Output "Access Token: $token"

Write-Output "Access Token: $token"

Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error.

At line:14 char:13

  • $response = Invoke-RestMethod -Uri $functionUrl -Method GET
  •         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    • FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Access Token: @{access_token=}

Could someone please help me understand what might be wrong and how to get the token from the app registration?

Azure Functions
Azure Functions

An Azure service that provides an event-driven serverless compute platform.


1 answer

Sort by: Most helpful
  1. Anonymous
    2025-05-29T10:53:24.3+00:00

    Hi Guy Levi,

    I tried to run your code in Azure function App and got 500 Internal Server error as below:

    [ "Error retrieving token: An attempt was made to access a socket in a way forbidden by its access permissions. (169.254.169.254:443)" ]

    In PowerShell Azure Functions, calling http://169.254.169.254 for managed identity can fail if the function App attempts to route the call via HTTPS instead of HTTP or applies a proxy, even on public network access.

    An attempt was made to access a socket in a way forbidden by its access permissions. (169.254.169.254:443)

    This error indicates something is redirecting the request to port 443 (HTTPS), even though the Invoke request is using HTTP.

    Hence as a workaround, you can use below PowerShell code with Az modules to generate access token in Function App using Managed Identity.

    run.ps1:

    
    param($Request, $TriggerMetadata)
    
     
    
     Connect-AzAccount -Identity | Out-Null
    
     
    
    $scope = "api://b2b532c5XXb537-d507914e592a" //APP ID or Client ID of App registration
    
     
    
    try {
    
        $tokenResponse = Get-AzAccessToken -ResourceUrl $scope
    
     
    
        Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    
            StatusCode = 200
    
            Body = @{
    
                access_token = $tokenResponse.Token
    
            } | ConvertTo-Json -Depth 3
    
        })
    
    }
    
    catch {
    
        Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    
            StatusCode = 500
    
            Body = @("Error retrieving token: $($_.Exception.Message)")
    
        })
    
    }
    
    

    requirements.ps1:

    @{
    
    	'Az.Accounts' = '2.12.1'
    
    }
    

    profile.ps1:

    
    Import-Module Az.Accounts 
    
    
    • `I have assigned below API permission to the Function App's managed identity:

    image

    • Able to generate the access token as below:

    image

    Hope it helps!


    Please do not forget to click "Accept the answer” and Yes wherever the information provided helps you, this can be beneficial to other community members.

    User's image

    If you have any other questions or still running into more issues, let me know in the "comments" and I would be happy to help you.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.