Skip to content

Instantly share code, notes, and snippets.

@lenart
Created November 15, 2018 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lenart/fa639ec5ac40c5d7324f2b5ecf450538 to your computer and use it in GitHub Desktop.
Save lenart/fa639ec5ac40c5d7324f2b5ecf450538 to your computer and use it in GitHub Desktop.
Postman auto fetch oAuth access token
// Add this script to collection's pre-request scripts
// Collection -> Edit -> Pre-request Scripts
// Automatically fetch oAuth access_token and store it for 1 hour
update_token = pm.environment.get("token_time");
if (typeof(update_token) == "undefined" || update_token <= Date.now()) {
console.log("Fetching new oAuth access token for user");
pm.sendRequest({
url: pm.environment.get("host") + pm.environment.get("token_path"),
method: 'POST',
header: {},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "grant_type", value: "password" },
{ key: "client_id", value: pm.environment.get("client_id") },
{ key: "client_secret", value: pm.environment.get("client_secret") },
{ key: "username", value: pm.environment.get("username") },
{ key: "password", value: pm.environment.get("password") },
]
}
}, function (err, res) {
if (res.code == 200) {
var expireIn = 60 * 60 * 1000; // 1 hour in milliseconds
pm.environment.set("admin_access_token", res.json().access_token);
pm.environment.set("token_time", Date.now() + expireIn);
}
else {
console.log(res.json());
pm.environment.set("token_time", null);
pm.environment.set("admin_access_token", null);
}
});
}
else {
console.log("Reusing existing oAuth access token");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment