Create Azure Service Principal And Get AAD Auth Token

In this post, I am trying to describe to create Service Principal in Azure using Powershell and generate auth token using postman REST call and Powershell.

We found ourself in a situation where we need to authenticate azure, Call Azure REST API when we are working with Azure. Applications like PowerShell scripts and .NET, JAVA or any other application need to authenticate azure in order to perform actions in azure. In order to call the REST API, we have to use an authentication token.
 
In this post, I will describe the following areas.
  1. Create Service Principal
  2. Generate Authtoken using Postman REST API call
  3. Generate AuthToken using Powershell

Create Service principle

 
What is Service Principal?
 
Service principles are non-interactive Azure accounts. Applications use Azure services should always have restricted permissions. Azure offers Service principals allow applications to login with restricted permission Instead of having full privilege in a non-interactive way.
 
Using Service Principal we can control which resources can be accessed.
 
For security reason, it’s always recommended to use service principal with automated tools rather than allowing them to log in with user identity
 
Create a Service Principal with PowerShell.
 
Note
For this demo we are using Azure RM PowerShell module
 
Create AD app
  1. #Create AD app  
  2. $dummyUrl = "https://dummy.dummy.com"  
  3. $passpowrd = "Qwerty@123!"  
  4. $securePassword = ConvertTo-SecureString -String $passpowrd -AsPlainText -Force  
  5. $app = New-AzureRmADApplication -DisplayName $dummyUrl `  
  6. -IdentifierUris $dummyUrl `  
  7. -HomePage $dummyUrl `  
  8. -Password $securePassword -Verbose  
  9. Create a Service Principal  
  10. #Create Service principal  
  11. New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId `  
  12. -DisplayName $dummyUrl `  
  13. -Password $securePassword `  
  14. -Scope "/subscriptions/<SUBSCRIPTION ID>" `  
  15. -Role Contributor `  
  16. -StartDate ([datetime]::Now) `  
  17. -EndDate $([datetime]::now.AddYears(1)) -Verbose  
This service principal is valid for one year from the created date and it has Contributor Role assigned. Further using this Service principal application can access resource under given subscription. We can scope to resources as we wish by passing resource id as a parameter for Scope.
 

View created AD app in Portal

  • Log in Portal
  • Go to Azure Active Directory -> App Registrations
  • We can find the created app as below,

    Create Azure Service Principal And Get AAD Auth Token
  • Once we click the app we will see app details as below,

    Create Azure Service Principal And Get AAD Auth Token
Keep these records as we need later.
 

Get Auth token by calling Rest API in Postman

  • Create a new Post Request
  • Create New POST request in Postman
  • Update Url as below
https://login.microsoftonline.com/{TENANTID}/oauth2/token
 
Create Azure Service Principal And Get AAD Auth Token
 
Replace {TENANTID} with tenantId we got when we create service principle.
 
Set the Request Body,
 
Select x-www-form-urlencoded radio,
 
Add following parameters,
 
Parameter Name Value
grant_type client_credentials
client_id APPLICATION / CLIENT ID WE GOT WHEN WE CREATE SERVICE PRINCIPLE
client_secret PASSWORD WE USED WHEN CREATING SERVICE PRINCIPLE IN ABOVE
resource https://management.azure.com/
 
Create Azure Service Principal And Get AAD Auth Token
 
Send the request and observe the result. You will receive output like below.
 
Create Azure Service Principal And Get AAD Auth Token
 
So we could receive Auth token (access_token) invoking Rest API in PowerShell. We can use this token as bearer token for Azure REST API.
 
Are you wondering what these properties are? Azure has good documentation for these properties here.
 

Get AuthToken with PowerShell

 
PowerShell function which uses Azure SDK.
 
This function uses Azure SDK API to create Auth token. Make sure you have Azure SDK for .Net is installed
  1. #This function generate auth token using azure sdk  
  2. Function GetAuthTokenUsingAzureSdk {  
  3.    Param (  
  4.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  5.       [String]$apiEndpointUri,  
  6.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  7.       [String]$tenantId,  
  8.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  9.       [String]$applicationId,  
  10.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  11.       [String]$secret  
  12.    )  
  13. try {  
  14.    $adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"  
  15.    [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null  
  16.    $authorityUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"  
  17.    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -   ArgumentList $authorityUri  
  18.    $credential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -   ArgumentList $applicationId, $secret  
  19.    return $authContext.AcquireTokenAsync($apiEndpointUri, $credential).Result.AccessToken;  
  20. }  
  21. catch {  
  22.    throw  
  23. }  
  24. }  
  25. $apiEndpointUri = "https://management.azure.com/"  
  26. $tenantId = "xxxxxx-xxxxx-xxxx-xxx-xxxx"  
  27. $applicationId = "xxxx-xxxx-xxxx-xxxx-xxxxx"  
  28. $secret = "xxxxxxxxxx"  
  29. $authToken = GetAuthTokenUsingAzureSdk -apiEndpointUri $apiEndpointUri -tenantId $tenantId -applicationId $applicationId -secret $secret  
  30. if (-   not $authToken) { throw "One of the provided login information is invalid 'tenantId: $tenantId', 'applicationId: $applicationId', 'secret: $secret' " }  
  31. Write-Host "Auth token by GetAuthTokenUsingAzureSdk :"  
  32. Write-Host $authToken -ForegroundColor Yellow  
Note
Make sure to update tenantId, application, and secret as we did the previous step.
 

Powershell function which invokes REST API

 
Invoking Azure REST API in PowerShell we can generate Auth token as below, 
  1. #This function generate auth token using REST api  
  2. Function GetAuthTokenInvokingRestApi {  
  3.    Param(  
  4.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  5.       [String]$tenantId,  
  6.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  7.       [String]$applicationId,  
  8.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  9.       [String]$secret,  
  10.       [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]  
  11.       [string]$apiEndpointUri  
  12. )  
  13. $encodedSecret = [System.Web.HttpUtility]::UrlEncode($secret)  
  14. $RequestAccessTokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"  
  15. $body = "grant_type=client_credentials&client_id=$applicationId&client_secret=$encodedSecret&resource=$apiEndpointUri"  
  16. $contentType = 'application/x-www-form-urlencoded'  
  17. try {  
  18.    $Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType $contentType  
  19.    Write-Output $Token  
  20.    }  
  21.    catch { throw }  
  22. }  
  23. $apiEndpointUri = "https://management.azure.com/"  
  24. $tenantId = "xxxxxx-xxxxx-xxxx-xxx-xxxx"  
  25. $applicationId = "xxxx-xxxx-xxxx-xxxx-xxxxx"  
  26. $secret = "xxxxxxxxxx"  
  27. $authToken = GetAuthTokenInvokingRestApi -apiEndpointUri $apiEndpointUri -tenantId $tenantId -applicationId $applicationId -secret $secret  
  28. if (-   not $authToken) { throw "One of the provided login information is invalid 'tenantId: $tenantId', 'applicationId: $applicationId', 'secret: $secret' " }  
  29. Write-Host "Auth token by GetAuthTokenInvokingRestApi :"  
  30. Write-Host $authToken -ForegroundColor Yellow  
  31. When we run above powerhsell script we can get auth tokens as below  

Summary

 
During our development life with Azure, we found our self in a situation where we need to authenticate Azure in order to communicate with azure. In order to use Azure Rest API, we have to pass Bearer token to authenticate.
 
So we need to generate auth token for this purpose. So in this post, we could have a look at arias where we can generate Auth token.
 
I think this might help developers. :)