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.
Estimated reading time: 3 minutes
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 Azure Bearer Token with Postman
To auto-generate an access token, I have the following configuration. In my environment, I have the following variables.
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.
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.