| | 0

How to generate a bearer access token for Azure REST access with username and password only – Feasibility test

It’s not so easy to get the bearer access token for Azure. The typical PowerShell command doesn’t return the token. However, you need it to talk directly via REST to Azure.

The “normal” way is to register your application within Azure Active Directory to authenticate a user. For a simple test (and an unattended/silent login without preparation) I found a way similar to PowerShell’s command “Login-AzureRmAccount”. PowerShell uses an internal well-known client id to authenticate a user to Azure (1950a258-227b-4e31-a9cf-717495945fc2).

1
2
3
4
5
6
7
8
9
10
$AccountName ="srvAccount-Desktops@xxxxxxxxxxxxxxxxxxxxxxx.onmicrosoft.com"
$Password = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$Response=Invoke-WebRequest -Uri "https://login.microsoftonline.com/Common/oauth2/token" -Method POST -Body $PayLoad
$ResponseJSON=$Response|ConvertFrom-Json
$ResponseJSON

The bearer token is in $ResponseJSON.access_token

Warning: This method is for testing only. Any change by Microsoft can break this procedure. I’m not sure if it’s a good idea/allowed to use this client id.

Hint: I used a service account which I added to my xxx.onMircosoft.com Azure AD. This account has designated rights in my subscription and can only see these resources. This account only exists in this directory so I’ve no problems with my account marcel.meurer@sepago.de, which is a personal and also a business account.

A short test: Enumerate all subscriptions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$Headers = New-Object "System.Collections.Generic.Dictionary"
$Headers.Add("Authorization", "Bearer "+$ResponseJSON.access_token)
$ResponseSubscriptions=Invoke-WebRequest -Uri "https://management.azure.com/subscriptions?api-version=2015-01-01" -Method GET -Headers $Headers
$ResponseSubscriptionsJSON=$ResponseSubscriptions|ConvertFrom-Json
$ResponseSubscriptionsJSON.value
Output:
--------------------------------------------
id                   : /subscriptions/31x00b3-9b23-451c-a041-xxxxxxxaead
subscriptionId       : 31xx00b3-9b23-451c-a041-xxxxxxxxxxaead
displayName          : Microsoft MVP Program
state                : Enabled
subscriptionPolicies : @{locationPlacementId=Public_2014-09-01; quotaId=MSDN_2014-09-01; spendingLimit=On}