Skip to content

Instantly share code, notes, and snippets.

@bizley
Created September 13, 2019 12:03
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 bizley/85370cad59b778832747c13dfeb1184c to your computer and use it in GitHub Desktop.
Save bizley/85370cad59b778832747c13dfeb1184c to your computer and use it in GitHub Desktop.
Pre-request for Postman to check if OAuth2 token expired and if so to refresh it.
let currentTime = Math.floor(Date.now() / 1000);
let tokenExpiration = pm.environment.get("token_expiration");
if (tokenExpiration && tokenExpiration <= currentTime) {
let apiUrl = pm.environment.get("api_url");
let refreshToken = pm.environment.get("refresh_token");
if (refreshToken) {
pm.sendRequest(
{
url: 'http://' + apiUrl + '/oauth/v2/token',
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'raw',
raw: JSON.stringify({
"client_id": "client_id",
"client_secret": "client_secret",
"refresh_token": refreshToken,
"grant_type": "refresh_token"
})
}
},
function (err, response) {
if (response.code == 200) {
let jsonData = response.json();
pm.environment.set("access_token", jsonData.access_token);
pm.environment.set("refresh_token", jsonData.refresh_token);
pm.environment.set("token_expiration", parseInt(jsonData.expires_in) + Math.floor(Date.now() / 1000));
} else {
console.log({"error": err, "response": response});
}
}
);
} else {
console.log("No refresh token");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment