-
-
Save knbknb/61e8bcd6759b9fd7a294e037dce3b701 to your computer and use it in GitHub Desktop.
Postman pre-request script to automatically get a bearer token from our custom software 'mDIS' and save it for reuse
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
// set these variables on the folder level | |
// also select Postman No-Authentication option, and then set your own HTTP Autorization Header | |
var url = pm.variables.get('baseUrl') + "/api/v1/auth/login"; | |
var username = pm.variables.get('username'); | |
var password = pm.variables.get('password'); | |
const echoPostRequest = { | |
url: url, | |
method: 'POST', | |
header: 'Content-Type:application/json', | |
body: | |
{ | |
mode: 'urlencoded', | |
urlencoded: [ | |
{ key: "username", value: username }, | |
{ key: "password", value: password }, | |
] | |
} | |
}; | |
var getToken = true; | |
if (!pm.variables.get('currentAccessToken')) { | |
console.info(url + ': Token missing, will get new token...') | |
} else { | |
getToken = false; | |
console.info(url + ': Token is good'); | |
} | |
console.log(echoPostRequest); | |
if (getToken === true) { | |
pm.sendRequest(echoPostRequest, function (err, res) { | |
if (err) { | |
console.log(err); | |
} else { | |
console.log('Saving the token') | |
var responseJson = res.json(); | |
pm.variables.set('currentAccessToken', responseJson.token) | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment