Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torstenek/e06e86aae17b9cf72d30d55de90f7ce7 to your computer and use it in GitHub Desktop.
Save torstenek/e06e86aae17b9cf72d30d55de90f7ce7 to your computer and use it in GitHub Desktop.
/*
Install this script as a pre-request Script on your Postman collection.
Define Auth_Url, and Basic_Auth as local variables on the collection.
Define OAuth_Token, OAuth_Timestamp, ExpiresInTime, OAUTH_USERNAME, OAUTH_PASSWORD and OAUTH_REFRESH_TOKEN
in the associated Postman environment.
*/
var tokenDate = new Date(2010, 1, 1);
var tokenTimestamp = pm.environment.get("OAuth_Timestamp");
if (tokenTimestamp) {
tokenDate = Date.parse(tokenTimestamp);
}
var expiresInTime = pm.environment.get("ExpiresInTime");
if (!expiresInTime) {
expiresInTime = 1800;
}
if ((new Date() - tokenDate) >= expiresInTime) {
pm.sendRequest({
url: pm.variables.get("Auth_Url"),
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': pm.variables.get("Basic_Auth")
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "grant_type", value: "refresh_token", disabled: false },
{ key: "client_id", value: pm.environment.get("OAUTH_USERNAME"), disabled: false },
{ key: "client_secret", value: pm.environment.get("OAUTH_PASSWORD"), disabled: false },
{ key: "refresh_token", value: pm.environment.get("OAUTH_REFRESH_TOKEN"), disabled: false }
]
}
}, function (err, res) {
pm.environment.set("OAuth_Token", res.json().access_token);
pm.environment.set("OAuth_Timestamp", new Date());
if (res.json().expires_in) {
expiresInTime = res.json().expires_in * 1000;
}
pm.environment.set("ExpiresInTime", expiresInTime);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment