Use the below script in Pre-Request Scripts of Postman to authenticate the Azure Service principal with ‘Client_Secret’ and save the access token in environment variable (access_token) for further use.

 

const accessTokenRequest = {  
  url: 'https://login.microsoftonline.com/'+ postman.getEnvironmentVariable("DirectoryId") + '/oauth2/token',
  method: 'POST',
  header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
     mode: 'urlencoded',
     urlencoded: [
            { key: "client_id", value: postman.getEnvironmentVariable("client_id") },
            { key: "client_secret", value: postman.getEnvironmentVariable("client_secret") },
            { key: "resource", value:postman.getEnvironmentVariable("resource") },
            { key: "grant_type", value: postman.getEnvironmentVariable("grant_type") },
        ]
      
    }
  };

console.log ("accessTokenRequest:",accessTokenRequest);

pm.sendRequest(accessTokenRequest, function (err, res) {

console.log(err ? err : res.json());

if (err === null) {
	var parseResponse = res.json();
    pm.environment.set('access_token', parseResponse.access_token);
 }
});

>> Set the following parameters in Environment variables

  • DirectoryId
  • client_id
  • client_secret
  • resource
  • grant_type
  • access_token

The example values are shown below

Note: If the endpoint accepts other than x-www-form-urlencoded then use the below code

const accessTokenRequest = {  
  url: 'https://login.microsoftonline.com/'+ postman.getEnvironmentVariable("DirectoryId") + '/oauth2/token',
  method: 'POST',
  header: 'Content-Type:application/json',
  body: {
     mode: 'application/json',
     raw: JSON.stringify(
            { client_id: postman.getEnvironmentVariable("client_id"),
              client_secret: postman.getEnvironmentVariable("client_secret") ,
              resource: postman.getEnvironmentVariable("resource") ,
              grant_type: postman.getEnvironmentVariable("grant_type") 
            })      
    }
  };

console.log ("accessTokenRequest:",accessTokenRequest);

pm.sendRequest(accessTokenRequest, function (err, res) {

console.log(err ? err : res.json());

if (err === null) {
	var parseResponse = res.json();
    pm.environment.set('access_token', parseResponse.access_token);
 }
});