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.
- Create Service Principal
- Generate Authtoken using Postman REST API call
- 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
- #Create AD app
- $dummyUrl = "https://dummy.dummy.com"
- $passpowrd = "Qwerty@123!"
- $securePassword = ConvertTo-SecureString -String $passpowrd -AsPlainText -Force
- $app = New-AzureRmADApplication -DisplayName $dummyUrl `
- -IdentifierUris $dummyUrl `
- -HomePage $dummyUrl `
- -Password $securePassword -Verbose
- Create a Service Principal
- #Create Service principal
- New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId `
- -DisplayName $dummyUrl `
- -Password $securePassword `
- -Scope "/subscriptions/<SUBSCRIPTION ID>" `
- -Role Contributor `
- -StartDate ([datetime]::Now) `
- -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,
- Once we click the app we will see app details as below,
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
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/
|
Send the request and observe the result. You will receive output like below.
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
- #This function generate auth token using azure sdk
- Function GetAuthTokenUsingAzureSdk {
- Param (
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$apiEndpointUri,
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$tenantId,
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$applicationId,
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$secret
- )
- try {
- $adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
- [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
- $authorityUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"
- $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" - ArgumentList $authorityUri
- $credential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" - ArgumentList $applicationId, $secret
- return $authContext.AcquireTokenAsync($apiEndpointUri, $credential).Result.AccessToken;
- }
- catch {
- throw
- }
- }
- $apiEndpointUri = "https://management.azure.com/"
- $tenantId = "xxxxxx-xxxxx-xxxx-xxx-xxxx"
- $applicationId = "xxxx-xxxx-xxxx-xxxx-xxxxx"
- $secret = "xxxxxxxxxx"
- $authToken = GetAuthTokenUsingAzureSdk -apiEndpointUri $apiEndpointUri -tenantId $tenantId -applicationId $applicationId -secret $secret
- if (- not $authToken) { throw "One of the provided login information is invalid 'tenantId: $tenantId', 'applicationId: $applicationId', 'secret: $secret' " }
- Write-Host "Auth token by GetAuthTokenUsingAzureSdk :"
- 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,
- #This function generate auth token using REST api
- Function GetAuthTokenInvokingRestApi {
- Param(
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$tenantId,
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$applicationId,
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [String]$secret,
- [Parameter(Mandatory)][ValidateNotNull()][ValidateNotNullOrEmpty()]
- [string]$apiEndpointUri
- )
- $encodedSecret = [System.Web.HttpUtility]::UrlEncode($secret)
- $RequestAccessTokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"
- $body = "grant_type=client_credentials&client_id=$applicationId&client_secret=$encodedSecret&resource=$apiEndpointUri"
- $contentType = 'application/x-www-form-urlencoded'
- try {
- $Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType $contentType
- Write-Output $Token
- }
- catch { throw }
- }
- $apiEndpointUri = "https://management.azure.com/"
- $tenantId = "xxxxxx-xxxxx-xxxx-xxx-xxxx"
- $applicationId = "xxxx-xxxx-xxxx-xxxx-xxxxx"
- $secret = "xxxxxxxxxx"
- $authToken = GetAuthTokenInvokingRestApi -apiEndpointUri $apiEndpointUri -tenantId $tenantId -applicationId $applicationId -secret $secret
- if (- not $authToken) { throw "One of the provided login information is invalid 'tenantId: $tenantId', 'applicationId: $applicationId', 'secret: $secret' " }
- Write-Host "Auth token by GetAuthTokenInvokingRestApi :"
- Write-Host $authToken -ForegroundColor Yellow
- 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. :)