How To: Obtain an OAuth2 Token from Azure REST API using Postman and JavaScript (PowerShell included too!)

I've been in the software industry for about a decade, currently working as an Azure DevOps Engineer in Human Healthcare. I hold a B.S. in Computer Science and am a Microsoft Azure Administrator. In my personal life I enjoy traveling, playing piano, running, reading, and spending time with family & friends.
This guide assumes you already have an App Registration with Client Secret created in Azure AD and that the app has sufficient scope to make requests. Reference
The Setup
From Postman, create a collection with the following
Variableson it.The values for
tenantId,clientSecret, andclientIdshould be obtained from your Azure account and the Client App Registration within Azure AD.

Copy & Paste the following JavaScript into the
Pre-request Scriptsection of the collection.The script will check if a
bearerTokenhas already been obtained (or if it's expired) and fetch a new one if needed. If the request was successful, thebearerTokenandbearerTokenExpiresOnvalues will be set on the collection.
if(!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) {
pm.sendRequest({
url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/token',
method: 'POST',
header: 'Content-Type: application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "grant_type", value: "client_credentials", disabled: false },
{ key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
{ key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
{ key: "resource", value: pm.collectionVariables.get("resource") || "https://management.azure.com/", disabled: false }
]
}
}, function (err, res) {
if(err) {
console.log(err);
} else {
let resJson = res.json();
pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_on);
pm.collectionVariables.set("bearerToken", resJson.access_token);
}
});
}
- From the collection's
Authorizationsection set the Type toBearer Tokenand specify{{bearerToken}}as the Token value. Make sure to save all changes.

Obtaining and Using the OAuth2 Token
The current setup ensures that all requests made within the Azure collection will automatically have a valid Oauth2 token. That said, the only thing left to do is create and send a request!
Create a new request within the collection and set it's
AuthorizationtoInherit auth from parent.
The request I'm making is to
https://management.azure.com/subscriptions/:subscriptionId/resourceGroups/:resourceGroupName/providers/Microsoft.Web/sites/:name?api-version=2022-03-01, however, you may want to make a different request depending on your app registration's assigned scope. See Azure REST API Reference for endpoint documentation.With an endpoint chosen, send the request and you should get a
200 OK.
And that's it, you can now use Azure's REST API using OAuth2!
Thanks for reading and until next time, happy coding!
Alternative Approach
If you're looking for a more programmatic approach, here's a PowerShell snippet that does the same thing (sets to $variables["bearerToken"]):
$variables = @{
"bearerToken" = $null
"bearerTokenExpiresOn" = 0
"tenantId" = "YOUR_TENANT_ID"
"clientId" = "YOUR_CLIENT_ID"
"clientSecret" = "YOUR_CLIENT_SECRET"
"resource" = "https://management.azure.com/"
}
if (-not $variables["bearerToken"] -or (Get-Date).ToUniversalTime().Ticks -gt [DateTime]::FromBinary($variables["bearerTokenExpiresOn"]).Ticks) {
$body = @{
grant_type = "client_credentials"
client_id = $variables["clientId"]
client_secret = $variables["clientSecret"]
resource = $variables["resource"]
}
try {
$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$($variables['tenantId'])/oauth2/token" -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
$variables["bearerToken"] = $response.access_token
$variables["bearerTokenExpiresOn"] = (Get-Date).AddSeconds($response.expires_on).ToUniversalTime().Ticks
} catch {
Write-Error $_.Exception.Message
}
}



