A few ways to acquire Azure access token with scripting languages

Whether you are a sysadmin, DevOps guy, Blue/Red team your work will likely require to acquire Azure access token to work with Azure resources via Azure REST API. Moreover, not all things can be done with compiled command packages like Azure CLI or PowerShell.

In this article, let’s explore a few common ways to quickly get Azure access token.

Azure CLI

Microsoft developed a command specific to getting Azure access token.  You just simply run

Condition: you must be authorized before you can gain access token.

Below is kind of dirty script to test access token by calling VM REST API

PowerShell

There is not any built-in cmdlet like Azure CLI above but you can make one for you by initializing RmProfileClient object.

Condition: you must be authorized before you can gain access token.

See sample below

Python

There are a few ways here. It depends on your situation for example you don’t want to put plain-text username/password or service principal info (client_secret). Instead you want interactive authorization like using device code input. Below is sample code to acquire access token using method acquire_token_with_device_code()

Condition: you must be authorized before you can gain access token.

If you already have client id and client secret of your service principal you can use acquire_token_with_client_credentials() . This is a common way when working with CICD pipeline. Below is the simple function to acquire access token

Managed Identity

If your virtual machine enables System Assigned Identity you can go execute the following PowerShell script on it to get access token.

Condition: you must have access or privilege to execute script in that virtual machine.

Not only PowerShell, Bash or Python can be done easily too.

This entry was posted in Security Automation and tagged , . Bookmark the permalink.

1 Response to A few ways to acquire Azure access token with scripting languages

  1. Pingback: Security Monitoring and Detection Tips for your Storage Account – Part 4

Leave a Reply