How to automatically set a Bearer Token for your Postman requests?

Hi @gpub1,

Initially, I saw the same error. I made few changes to my script and it worked.
Try the below pre-request script. Add the β€˜Token’ variable as an environment variable.

var authServiceUrl = pm.environment.get('TOKEN_URL');
var cname = pm.environment.get('UNAME');
var cpword = pm.environment.get('PWD_ENCRYPTED');
var cID = pm.environment.get('CLIENT_ID');
var cSECR = pm.environment.get('CLIENT_SECRET');

const getTokenRequest = {
  method: 'POST',
  url: authServiceUrl+'/token',
  header: 'Content-Type:application/x-www-form-urlencoded',
  body: {
      mode: 'urlencoded',
      urlencoded: [
          { key: 'username', value: cname },
          { key: 'password', value: cpword },
          { key: 'client_id', value: cID },
          { key: 'client_secret', value: cSECR },
      ]
  }
};

pm.sendRequest(getTokenRequest, (err, response) => {
  const jsonResponse = response.json();
  const newAccessToken = jsonResponse.access_token;

  pm.variables.set('Token', newAccessToken);
});
2 Likes