Auto-Generate a Bearer Token for Each Azure REST API Request with Postman

In this Postman and Azure REST API, I will show you how to auto-generate a bearer token for each Azure REST API request with Postman.

Postman API client allows us to develop API requests to many cloud services using an intuitive interface.

When it comes to Azure, We can use the Azure REST API protocol to create and manage any service on Azure using API.

In my previous post, I showed how to Create an App Registration for Microsoft Azure REST API.

If you’re familiar with Azure REST API, one of the steps to create an API request is to generate a temporary access token.

Creating an access token is a manual process that must be repeated every hour when the token expires.

In this post, I will show you how to use a Pre-Request script in Postman to auto-generate an access token before sending a request.

Auto-Generate a Bearer Token for Each Azure REST API Request with Postman

To auto-generate an access token, I have the following configuration. In my environment, I have the following variables.

Varialbes list with Bearer Token

The variable BearerToken needs to be left empty.

I have the following JavaScript script on my collection page under the Pre-Request script. Please note that the values in the script need to match the values in the environment variables.

Pre-request script - Postman

Copy the script below.

const tokenExpired = !pm.environment.get("bearerToken") || Date.now() > pm.environment.get("bearerTokenExpiresOn") * 1000;

if (tokenExpired) {
    const tenantId = pm.environment.get("tenantId");
    const client_id = pm.environment.get("client_id");
    const client_secret = pm.environment.get("client_secret");
    const resource = pm.environment.get("resource") || "https://management.azure.com/";

    pm.sendRequest({
        url: `https://login.microsoftonline.com/${tenantId}/oauth2/token`,
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: {
            mode: 'urlencoded',
            urlencoded: [
                { key: "grant_type", value: "client_credentials" },
                { key: "client_id", value: client_id },
                { key: "client_secret", value: client_secret },
                { key: "resource", value: resource }
            ]
        }
    }, (err, res) => {
        if (err) {
            console.log(err);
        } else {
            const { expires_on, access_token } = res.json();
            pm.environment.set("bearerTokenExpiresOn", expires_on);
            pm.environment.set("bearerToken", access_token);
        }
    });
}

To use the auto-generated token in a REST request, set the Auth Type as shown below.

Conclusion

The goal of this post is to show you how to automate API tasks and save time. To get the script to work, make sure you specify the variable names currently and, most importantly, set the auth type to use the BearerToken variable.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.