How to Get Access Token Using Azure CLI

In modern cloud environments, securing access to resources often involves the use of access tokens. Azure CLI provides a straightforward way to obtain these tokens, which can be used to authenticate API calls to Azure services. This blog will guide you through the process of obtaining an access token using Azure CLI, discuss the difficulties associated with using APIs directly with client credentials, and provide a script to streamline the process.

Why Use Access Tokens?

Access tokens are critical for ensuring secure access to Azure resources. They authenticate the identity of the caller and authorize them to perform specific actions on the resources. Using Azure CLI to get these tokens simplifies the process, especially when working with multiple Azure services and APIs.

Use Case

Instead of invoking separate API from OAuth, we can directly get the AccessToken from Az CLI Itself

Step-by-Step Guide to Get Access Token Using Azure CLI

Install Azure CLI, Ensure you have Azure CLI installed. You can download and install it from the official Azure CLI page.

az --version

Login to Azure: Log in to your Azure account using the az login command. This will open a browser window for you to authenticate.

az login

If you are using a service principal (non-interactive login), use.

az login --service-principal --username <ClientID> --password <ClientSecret> --tenant <TenantID>

Set the Subscription

If you have multiple subscriptions, set the active subscription to the one you want to work with.

az account set --subscription <YourSubscriptionID>

Get Access Token, Use the following command to obtain the access token.

$accessToken = az account get-access-token --resource=https://management.azure.com/ --query accessToken --output tsv

Output

Note. I have attached the full script with the blog.

Obtaining access tokens using Azure CLI simplifies the process of authenticating API calls to Azure services. While using client credentials directly can pose several challenges, leveraging Azure CLI streamlines token management and enhances security. By following the steps and using the provided script, you can easily integrate this process into your workflows, ensuring secure and efficient access to your Azure resources.