You can leverage Postman "Pre-request script" to automatically acquire token and pass it as auth header to your API like below. Here is the script (replace the {placeholder} with your actual values).
pm.environment.set("tenantId", "{your tenant id}");
pm.environment.set("client_credentials", "client_credentials");
pm.environment.set("clientId", "{your client id}");
pm.environment.set("clientSecret", "{your client secret}");
pm.environment.set("scope", "{your scope}");
pm.sendRequest({
url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/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.environment.get("clientId"), disabled: false},
{key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false},
{key: "scope", value: pm.environment.get("scope"), disabled: false}
]
}
}, function (err, res) {
pm.globals.set("bearerToken", res.json().access_token);
console.log(pm.globals.get("bearerToken"));
});
- Set Authorization header to refer a global variable 'Bearer {<!-- -->{bearerToken}}' like below:
- Set the above global variable from pre-request script like below: