Created
September 13, 2019 12:03
-
-
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.
This file contains hidden or 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
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