Since a Bearer Token has a life of 12 hours. I made additions to script to get tokens only when they expire.
const tokenUrl = pm.environment.get( 'api-url' ) + '/oauth/token';
const clientId = pm.environment.get("pat-id");
const clientSecret = pm.environment.get("pat-secret");
const getTokenRequest = {
method: 'POST',
url: tokenUrl,
body: {
mode: 'formdata',
formdata: [
{ key: 'grant_type', value: 'client_credentials' },
{ key: 'client_id', value: clientId },
{ key: 'client_secret', value: clientSecret }
]
}
};
var moment = require('moment');
if(!pm.environment.has('time')){
pm.environment.set('time',moment());
}
if(moment(pm.environment.get('time')) < moment())
{
var time = moment();
time.add(12,'hours');
pm.environment.set('time',time);
pm.sendRequest(getTokenRequest, (err, response) => {
const jsonResponse = response.json();
const newAccessToken = jsonResponse.access_token;
pm.environment.set('access_token', newAccessToken);
});
}