Skip to content

Instantly share code, notes, and snippets.

@borjapazr
Created April 21, 2020 08:14
Show Gist options
  • Save borjapazr/d8650f0312708791ff62ead641639ef4 to your computer and use it in GitHub Desktop.
Save borjapazr/d8650f0312708791ff62ead641639ef4 to your computer and use it in GitHub Desktop.
Postman OAuth 2.0 pre-request with 'password' grant type
const postRequest = {
url: pm.collectionVariables.get('token_url'),
method: 'POST',
header: 'Content-Type:application/x-www-form-urlencoded; charset=utf-8',
body: {
mode: 'urlencoded',
urlencoded: [
{
key: 'client_id',
value: pm.collectionVariables.get('client_id'),
},
{
key: 'client_secret',
value: pm.environment.get('client_secret'),
},
{
key: 'scope',
value: pm.environment.get('scope'),
},
{
key: 'username',
value: pm.collectionVariables.get('user'),
},
{
key: 'password',
value: pm.collectionVariables.get('api_key'),
},
{
key: 'grant_type',
value: 'password',
},
{
key: 'auth_method',
value: 'password',
},
],
},
};
var getToken = true;
if (!pm.environment.get('access_token_expiry') || !pm.environment.get('current_access_token')) {
console.log('Token or expiry date are missing');
} else if (pm.environment.get('access_token_expiry') <= new Date().getTime()) {
console.log('Token is expired');
} else {
getToken = false;
console.log('Token and expiry date are all good');
}
if (getToken === true) {
pm.sendRequest(postRequest, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token and expiry date');
var responseJson = res.json();
pm.environment.set('current_access_token', responseJson.access_token);
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.environment.set('access_token_expiry', expiryDate.getTime());
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment