Created
August 10, 2020 18:06
-
-
Save landy/8c30f7b804301f54c28a028c32bf39e0 to your computer and use it in GitHub Desktop.
Load Bearer token on each postman request
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
//add this as pre-request script on postman collection | |
const moment = require("moment") | |
const { | |
apiRoot, | |
authPath, | |
username, | |
password, | |
bearerTokenValidUntil | |
} = pm.variables.toObject(); | |
const req = { | |
url: apiRoot + "/" + authPath, | |
method: "POST", | |
header: { | |
'Content-Type': 'application/x-www-form-urlencoded' | |
}, | |
body: { | |
mode: "urlencoded", | |
urlencoded: [ | |
{key: "grant_type", value: "password"}, | |
{key: "username", value: username}, | |
{key: "password", value: password} | |
] | |
} | |
} | |
const resHandler = (err, res) => { | |
const {access_token, ".expires" : expires} = res.json() | |
pm.environment.set("bearerToken", access_token); | |
pm.environment.set("bearerTokenValidUntil", expires); | |
} | |
if (!bearerTokenValidUntil || moment(bearerTokenValidUntil).isBefore(moment())) { | |
pm.sendRequest(req, resHandler); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment