Skip to content

Instantly share code, notes, and snippets.

@ddieppa
Created August 16, 2021 20:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ddieppa/af2b83399bb5550fc0d0f2ca19241428 to your computer and use it in GitHub Desktop.
Save ddieppa/af2b83399bb5550fc0d0f2ca19241428 to your computer and use it in GitHub Desktop.
Postman retry the token if expired Pre-request script

Postman get token if expired

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

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