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

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

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

  1. From Postman, create a collection with the following Variables on it.

    The values for tenantId, clientSecret, and clientId should be obtained from your Azure account and the Client App Registration within Azure AD.

  1. Copy & Paste the following JavaScript into the Pre-request Script section of the collection.

    The script will check if a bearerToken has already been obtained (or if it's expired) and fetch a new one if needed. If the request was successful, the bearerToken and bearerTokenExpiresOn values 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);
        }
    });
}
  1. From the collection's Authorization section set the Type to Bearer Token and 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!

  1. Create a new request within the collection and set it's Authorization to Inherit 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.

  2. 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
    }
}