Skip to content

Instantly share code, notes, and snippets.

@riosengineer
Created January 31, 2025 20:25
Show Gist options
  • Save riosengineer/d456800721c4532292550808f0f74326 to your computer and use it in GitHub Desktop.
Save riosengineer/d456800721c4532292550808f0f74326 to your computer and use it in GitHub Desktop.
Entra token request with MI on App Service to API endpoint
# Entra API resource URI
$resource = "api://YOUR_URI"
$endpoint = $env:IDENTITY_ENDPOINT
$header = $env:IDENTITY_HEADER
$apiVersion = "2019-08-01"
$headers = @{
'X-Identity-Header' = $header
'Content-Type' = 'application/x-www-form-urlencoded'
}
# Construct the URL to get the token
$url = "$($endpoint)?api-version=$apiVersion&resource=$resource"
try {
# Get the bearer token
$response = Invoke-RestMethod -Method Get -Uri $url -Headers $headers
$bearerToken = $response.access_token
# Define the API endpoint and subscription key
$apiUrl = "https://api.contoso.com/v1/...."
$subscriptionKey = "APIM_SUB_KEY"
# Set the headers for the API call
$apiHeaders = @{
'Authorization' = "Bearer $bearerToken"
'Ocp-Apim-Subscription-Key' = $subscriptionKey
}
# Make the API call
$apiResponse = Invoke-RestMethod -Method Get -Uri $apiUrl -Headers $apiHeaders
Write-Output $apiResponse
} catch {
Write-Output "Exception Message: $($_.Exception.Message)"
if ($_.Exception.Response) {
Write-Output "Status Code: $($_.Exception.Response.StatusCode)"
Write-Output "Status Description: $($_.Exception.Response.StatusDescription)"
Write-Output "Response Content: $($_.Exception.Response.Content)"
} else {
Write-Output "No response received from the server."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment