HomeBlog ArticlesAbout Me

Authentication for Azure REST APIs using Azure AD Service Principals

By Aby Thannikal Joseph
Published in Azure
December 18, 2022
2 min read
Authentication for Azure REST APIs using Azure AD Service Principals

In this article, we will explore how to make a REST API call to Azure resources to manipulate (CRUD) them.

Azure REST APIs require authentication that confirms that we or the application as the user has the appropriate permissions to perform the given action - this is achieved by creating a Service Principal (SPN) in Azure Active Directory (AD) and acquiring a Bearer Token to authenticate

Creating a Service Principal and generating ClientID/ ClientSecret(via Portal)


spn client creation 1

spn client creation 2

spn client creation 3

  • There are five inputs to be noted:

    • Client ID (Application ID)
    • Client Secret (Client Secret can be generated from the following steps)
    • Tenant ID (Directory ID)
    • Subscription ID (Obtained from the Subscriptions)

spn client creation 4

Add a Role Assignment with the Service Principal (via Portal)


The Service Principal created only defines the object and would need to be Role assigned to which resource that is allowed via the object to be accessed.

  • Navigate to the Resource Group (or Subscription/Resource) >> Access Control (IAM) >> Add Role Assignment
    spn role assignment 1
  • Select the accesss role required, and search and select the Service Principal created earlier.
    spn role assignment 2
  • The Role is now assigned to the Resource Group under Role Assignment on successful assignment
    spn role assignment 3

Creating SPN and assigning a Role, and generating a Client Secret (via Azure CLI)


The Azure CLI can be used to create the Service Principal, assign the role, and then create the required Client ID and with the Cloud Shell CLI or local Azure CLI (Pretty much avoiding going through Portal as above!) This section can be skipped if you have already created the SPN, assinged role and have the Client ID and Client Secret generated.

az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/<SUBSCRIPTION-ID>/resourceGroups/<RESOURCE-GROUP-NAME>"

powershell ad creation output Note the Client Secret safely as it will be displayed only once.

  • Successful assignment of the Role can be checked by navigating to the Resource >> Access Control (IAM) >> Role Assignments and the SPN should be listed with the correct access role.

Acquiring an AD Access Token


The Access Token can be acquired by using any REST Client, in this example we will use PostMan and an example using PowerShell command

PostMan

  • Launch Postman and request a POST call to https://login.microsoftonline.com/{{tenant-id}}/oauth2/token with
    • ContentType = x-www-form-urlencoded
    • grant_type = client_credentials
    • client_id = Generated from the steps before (appID in the Command output or Application Client ID from the portal)
    • client_secret = Generated from the client password generation step (password noted in the Command output)
    • resource = https://management.azure.com/ (depends on the resource being accessed, Refer API Documentation)

postman acquire token 01

Send the Request and a successful response returns with 200 OK and the access_token in the Response body. Note the access_token value as this will be passed into the header to authenticate next. postman acquire token 02

PowerShell

The AD Bearer Token can also be acquired by the Powershell commands (without using Postman)

$AccessToken = Invoke-RestMethod -Method Post -Uri $RequestURL -Body $body -ContentType 'application/x-www-form-urlencoded'

$TenantID = "xxxx-xxxx-xxxx-xxxx-xxxx"
$RequestURL =  "https://login.microsoftonline.com/$TenantID/oauth2/token"
$ContentType = "application/x-www-form-urlencoded"
$grant_type = "client_credentials"
$client_id = "xxxxxxxxx"
$client_secret = "xxxxxxxxx"
$resource = "https://management.azure.com/"
$Body = "grant_type=$grant_type&client_id=$client_id&client_secret=$client_secret&resource=$resource"
$AccessTokenResponseBody = Invoke-RestMethod -Method Post -Uri $RequestURL -Body $Body -ContentType $ContentType
echo $AccessTokenResponseBody.access_token

I have broken it down into variables to demonstrate how the request is constructed.

Testing Access with Postman


As an example, we will look at the REST API to create Tags for a Resource group. The API documentation for this at Resource Groups - Create Or Update - REST API (Azure Resource Management) | Microsoft Learn

Set the Header to “Authorization” and value as “Bearer <TokenValue>” (note the space between the Bearer and Token

PUT https://management.azure.com/subscriptions/{{subscription-id}}/resourcegroups/{{resource-group}}?api-version=2021-04-01
Request Body:
{
    "location": "uksouth",
    "tags": {
        "env": "QA"
    }
}

postman request example

and the response returns 200 OK and Succeeded state for this example.

postman response example

The requested “env” tag is successfully created in the Resource Group via Azure REST API! 😀

azure portal tag created

Refer the Azure REST API Documentation for other actions

Common Issues


  • If you forget/miss to copy the Client Secret, you can always reset it from Azure CLI
az ad app credential reset --id <AppID/ClientID>

Add —append flag if you want to create the new secret as addtional secret

  • Resource access doesn’t have permission
{
    "error": {
        "code": "AuthorizationFailed",
        "message": "The client 'xxx-xxx-xxx-xxx' with object id 'xxx-xxx-xxx-xxx' does not have authorization to perform action 'Microsoft.Resources/subscriptions/resourcegroups/write' over scope '/subscriptions/xxx-xxx-xxx-xxx/resourcegroups/xxx-xxx-xxx-xxx' or the scope is invalid. If access was recently granted, please refresh your credentials."
    }
}

Check if the created SPN is correctly role assigned (Role Assignment) to the resources accessed, or generate a new Bearer token if changes were recently made.

Hope that was helpful! :)


Tags

azure
Previous Article
Generalize an Azure Virtual Machine to create a VM Image
Aby Thannikal Joseph

Aby Thannikal Joseph

Table Of Contents

1
Creating a Service Principal and generating ClientID/ ClientSecret(via Portal)
2
Add a Role Assignment with the Service Principal (via Portal)
3
Creating SPN and assigning a Role, and generating a Client Secret (via Azure CLI)
4
Acquiring an AD Access Token
5
Testing Access with Postman
6
Common Issues
Aby Thannikal Joseph © 2022, All Rights Reserved.

Legal Stuff

Privacy NoticeCookie PolicyTerms Of Use

Social Media