Postman Authentication in Pre- run script Fails - Automatic token generation in single request

I am trying to create a pre-run script which gets the bearer token and sets it to the environment variable. The variable is used for authentication for PostDetails request.

Facing the Error : jsonerror :Unexpected token '<' at 3:1 <!-- Copyright (C) Microsoft Corporation. All rights reserved. --> ^

Below is the script:

// get the collection 
var sdk = require('postman-collection');

// construct the bearer token  request
var tokenRequest = new sdk.Request({
    url: 'https://login.microsoftonline.com/tenantname.com/oauth2/token', 
    method: 'GET',
    header: [
        new sdk.Header({
            key: 'content-type',
            value: 'application/x-www-form-urlencoded'
        }),
        new sdk.Header({
            key: 'Connection',
            value: 'keep-alive'
        }),
    ],
    body: {
        mode: 'application/x-www-form-urlencoded',
        raw: JSON.stringify({
            client_id: 'cccccccccccccccccccccccccccccc',
            client_secret: 'ssssssssssssssssssssssssss',
            grant_type: 'Client_credentials',
            resource: 'https://usnconeboxax1aos.cloud.onebox.dynamics.com'
        })
    }

  });

// send bearer token  request
 pm.sendRequest(tokenRequest, function (err, response) {
      if (err) {
          throw err;
      }
      
      if (response.code !== 200) {
          throw new Error('Could not log in.');
      }
      pm.environment.set("token", response.json().access_token);
      console.log('New token has been set: ${response.json().access_token}');
  });

Kindly let me know whats wrong or missing and how it can be troubleshooted.

Hey @SwathySubramani

Welcome to the community! :trophy:

I think something like this added to the pre-request script might help:

var tokenRequest = {
    url: 'https://login.microsoftonline.com/tenantname.com/oauth2/token', 
    header: {
            'Content-Type':'application/x-www-form-urlencoded',
            'Connection':'keep-alive'
    },
    body: {
        mode: 'application/x-www-form-urlencoded',
        urlencoded : [
            { key: 'client_id', value: 'cccccccccccccccccccccccccccccc'},
            { key: 'client_secret', value: 'ssssssssssssssssssssssssss'},
            { key: 'grant_type', value: 'Client_credentials'},
            { key: 'resource', value: 'https://usnconeboxax1aos.cloud.onebox.dynamics.com'}
        ]
    }
  };

// send bearer token  request
pm.sendRequest(tokenRequest, function (err, response) {
    if (err) {
        throw err;
    }
      
    if (response.code !== 200) {
        throw new Error('Could not log in.');
    }
    pm.environment.set("token", response.json().access_token);
    console.log(`New token has been set: ${response.json().access_token}`);
});

This is a handy resource when using pm.sendRequest():

@dannydainton: Thanks for the quick resolution. The shared script worked.

1 Like