Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate to Azure REST API using username and password (no App Id)

I need to acquire access token for accessing resources in Azure (https://management.azure.com endpoint) using REST API. Every article a have read, was counting with Appliction Id. In my case, the Azure tenant was just created (programatically) and I have to create some resources in it.

Only thing I have is tenant id, subscription id, user name and password of admin account. How can I authenticate using only information I have? How it works in PowerShell, that does not need to use an Application Id?

like image 521
Lukas Nespor Avatar asked Mar 07 '23 18:03

Lukas Nespor


1 Answers

Based on my knowledge, it is impossible. As junnas said, even you use user/password authentication, client id is also required.

It is easy for you to create a service principal on Azure, you could check this link.

After the sp is created, you will get the client id, client secret. You also need give the sp Owner role on subscription, you could check this link.

Now, you could use the sp to call rest api in Power Shell, for example.

##get token
$TENANTID=""
$APPID=""
$PASSWORD=""
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token

##set subscriptionId and resource group name
$subscriptionId=""
$resourcegroupname="shui5"

$Headers=@{
    'authorization'="Bearer $token"
    'host'="management.azure.com"
    'contentype'='application/json'
}
$body='{
    "location": "northeurope",
     "tags": {
        "tagname1": "test-tag"
    }
 }'
Invoke-RestMethod  -Uri "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${resourcegroupname}?api-version=2015-01-01"  -Headers $Headers -Method PUT -Body $body 
like image 76
Shui shengbao Avatar answered Mar 16 '23 17:03

Shui shengbao