This is a way to before every request check if the auth token is expired and retrieve a new one, update the variable if needed
Created
August 16, 2021 20:45
-
-
Save ddieppa/af2b83399bb5550fc0d0f2ca19241428 to your computer and use it in GitHub Desktop.
Postman retry the token if expired Pre-request script
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
const appUserId = pm.environment.get("appuserid"); | |
const manufacturerId = pm.environment.get("manufacturerid"); | |
const appId = pm.environment.get("appid"); | |
const tokenUrl = pm.environment.get("token_url"); | |
let expiresInTime = pm.environment.get("expires_in"); | |
if (!expiresInTime) { | |
const defaultExpirationTime = 86400; | |
console.log( | |
`Setting token expiration time to default: ${defaultExpirationTime} ` | |
); | |
expiresInTime = defaultExpirationTime; //Set expire time to default | |
} | |
console.log(new Date().getTime()); | |
const authRequest = { | |
url: tokenUrl, | |
method: "GET", | |
header: { | |
Accept: "application/json", | |
"Content-Type": "application/json", | |
"x-appuserid": appUserId, | |
"x-manufacturerid": manufacturerId, | |
"x-appid": appId, | |
}, | |
}; | |
if (expiresInTime <= new Date().getTime()) { | |
console.log("Token is expired"); | |
pm.sendRequest(authRequest, (error, response) => { | |
const responseJson = response.json(); | |
console.log(error ? error : responseJson); | |
pm.environment.set("token", responseJson.access_token); | |
if (responseJson.expires_in) { | |
var expiryDate = new Date(); | |
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in); | |
pm.environment.set("expires_in", expiryDate.getTime()); | |
} | |
}); | |
} else { | |
console.log("Token expire date is OK"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment