Created
March 19, 2019 15:58
-
-
Save PatrickWalker/4e77ce4527c95c5a765a27bd7f69b1e4 to your computer and use it in GitHub Desktop.
Postman Prerequest Script to store an auth token before each API 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
// we use this to set an expiry on the token | |
var currTime = new Date().getTime(); | |
// If there is an expiry value and it's before current time then we've expired | |
if (pm.globals.get("tokenExpiry") !== '' && pm.globals.get("tokenExpiry") <= currTime){ | |
console.log('Token Expiry Exceeded. Clearing token'); | |
pm.globals.set("token",'') | |
} | |
// If we have a valid token then we don't need to request it we'll reuse it | |
if (pm.globals.get("token") !== ''){ | |
console.log("Auth Token. Set So Not logging in again"); | |
} else { | |
// send request to auth | |
pm.sendRequest({ | |
url: 'http://' + pm.variables.get("host") + '/api/login', | |
method: 'POST', | |
header: { | |
'content-type': 'application/json' | |
}, | |
body: { | |
mode: 'raw', | |
raw: JSON.stringify({ | |
userName: pm.variables.get("username"), | |
password: pm.variables.get("password") }) | |
} | |
}, function (err, res) { | |
if (err) { console.log(err); | |
console.log('res : ' + res); | |
} | |
else{ | |
// if it's a 401 then we can clear the token and expiry out | |
// although really this should maybe be in the 'test' section after the main request as | |
// it's that 401 we would care more about | |
if (res.code === 401) { | |
console.log('clearing token'); | |
pm.globals.set("token",''); | |
pm.globals.unset("tokenExpiry"); | |
}else { | |
// set the token | |
pm.globals.set("token",res.json().token.mintedToken); | |
// set the expiry for 30 seconds from the start of this request | |
pm.globals.set("tokenExpiry",(currTime + 30000)); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment