Friday, April 22, 2022

Just Give Me an Access Token

Emerging OpportunitiesEmerging Opportunities

Use the Azure CLI to Get Access Tokens

One of my least favorite parts about developing custom APIs secured with Azure AD is figuring out how to acquire an access token when I am testing or debugging. Usually, this involves creating additional client app registrations, managing callback URLs, creating (and properly handling) secret keys, etc. In this video, I'll demonstrate how to use the Azure CLI as a client that can quickly and easily acquire access tokens for your custom APIs.

 

YouTube Video: https://youtu.be/iu_6H6fCkwI 

 

Try It!

  • First, I'll assume you already have an API project and created an app registration for it in Azure AD. Also, make sure you've assigned an Application ID URI and exposed a delegated scope. For more information (and a sample) see the Protected web api Overview.
  • Next, register a Service Principal in your Azure AD tenant for the Azure CLI. This will allow you to grant custom permissions to it.
  • Finally, grant permissions to your API and then use the CLI to get an access token for it. 

Use this PowerShell script to perform these steps.

 

 

$appId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" #global appId for az CLI
$apiId = "your-app-id-here" #appId of your custom API
$requestScope = "api://your-app-id-here/.default" #scope exposed by your custom API app registration

## First time only
az login
az ad sp create --id $appId
az ad app permission grant `
  --id $appId `
  --api $apiId `
  --scope "your-scope-name" #example: "access_as_user" or "user_impersonation"

## Get new token
az account get-access-token --scope $requestScope --query accessToken

 

 

Hopefully you find this to be a useful time saver!

Posted at https://sl.advdat.com/3v62fI0https://sl.advdat.com/3v62fI0