Saturday, September 9, 2023

How to invoke Azure Management API with Access token using AZ CLI


#### list of steps to invoke Azure Management API with Azure access token using AZ CLI.

1. log into Azure  using Az CLI 
2. Get access token using account get-access-token 
3. add bearer accesstoken as authorization Header
4. Invoke Azure Managment API 

```sh

az login
$subId=(az account list --query "[?isDefault].id" )|ConvertFrom-Json
$accesstoken =  [string](az account get-access-token | ConvertFrom-Json).accessToken
$headers = @{ Authorization = "Bearer $accesstoken" }
$url="< Azure Management API >"
$r= Invoke-WebRequest  -Uri  $url -Headers $headers
If ($r.StatusCode -eq 200 ) {($r.Content |ConvertFrom-Json).value}

# Replace  < Azure Management API > with your values  
```

Example: 

```sh
az login
$subId=(az account list --query "[?isDefault].id" )|ConvertFrom-Json
$accesstoken =  [string](az account get-access-token | ConvertFrom-Json).accessToken
$headers = @{ Authorization = "Bearer $accesstoken" }
$url="https://management.azure.com/subscriptions/$subId/providers/Microsoft.Compute/locations/eastus/runCommands?api-version=2022-11-01"
$r= Invoke-WebRequest  -Uri  $url -Headers $headers
If ($r.StatusCode -eq 200 ) {($r.Content |ConvertFrom-Json).value}
```
________


No comments:

Post a Comment