Last active
May 14, 2024 11:13
-
-
Save srikiranvelpuri/aca507f9441feeef831b53959e12daaf to your computer and use it in GitHub Desktop.
Postman PreRequestScript to check if an OAuth token has expired and, if so, refreshes it by making a new authentication request.
This file contains 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 expiryDate = new Date(pm.environment.get('tokenExpiryDate')); | |
const currDate = new Date(Date.now()); | |
const isTokenExpired = (isNaN(expiryDate) || expiryDate) < currDate; | |
if(isTokenExpired){ | |
pm.sendRequest({ | |
url: pm.globals.get("oAuthUrl"), | |
method: 'POST', | |
header: { | |
'Authorization': pm.globals.get("basicAuth"), | |
}, | |
body:{ | |
mode: 'urlencoded', | |
urlencoded: [ | |
{ key: "grant_type", value: "password" }, | |
{ key: "username", value: pm.globals.get("username") }, | |
{ key: "password", value: pm.globals.get("password") } | |
] | |
} | |
}, function (err, res) { | |
if(err) return | |
const response = res.json(); | |
var authToken = response.access_token; | |
const currDate = new Date(); | |
var tokenExpiry = new Date(currDate.getTime() + 1000 * (response.expires_in)); | |
pm.globals.set("tokenSetFrom", "PreRequestScript") | |
pm.environment.set("tokenExpiryDate", tokenExpiry); | |
pm.environment.set("authToken", authToken); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment