Created
October 28, 2018 13:16
-
-
Save zhenja/84fdb7f12dfa377c2ce5397f1f1d801a to your computer and use it in GitHub Desktop.
Postman Pre-request Script to automatically get a Bearer Token from OAuth and save it for reuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const moment = require('moment'); | |
const getAuthorization = { | |
url: pm.environment.get("tokenBaseURL") + '/ia2oauth/token', | |
method: 'POST', | |
header: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
}, | |
body: { | |
mode: 'urlencoded', | |
urlencoded: [ | |
{key: 'grant_type', value: 'password'}, | |
{key: 'username', value: pm.globals.get("user-id")}, | |
{key: 'password', value: pm.globals.get("user-pw")}, | |
{key: 'client_secret', value: pm.environment.get("client_secret")}, | |
{key: 'client_id', value: pm.environment.get("client_id")}, | |
{key: 'accountType', value: 'USER'} | |
] | |
} | |
}; | |
var getToken = true; | |
if (!_.has(pm.environment.toObject(), 'AccessTokenExpiry') | |
|| !_.has(pm.environment.toObject(), 'authorization') | |
|| pm.environment.get('AccessTokenExpiry') <= moment().valueOf()) { | |
} else { | |
getToken = false; | |
} | |
console.log('getToken: ' + getToken); | |
if (getToken) { | |
pm.sendRequest(getAuthorization, (err, res) => { | |
console.log('res: ' + res.json()); | |
if (err === null) { | |
pm.environment.set('authorization', `Bearer ${res.json().access_token}`); | |
console.log('authorization: ' + pm.environment.get("authorization")); | |
var expiryDate = moment().add(res.json().expires_in, 's').valueOf(); | |
pm.environment.set('AccessTokenExpiry', expiryDate); | |
} else { | |
console.log('error: ' + err); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment