Skip to content

Instantly share code, notes, and snippets.

@hugomota
Created July 24, 2020 14:48
Show Gist options
  • Save hugomota/946a71d28ab39985c8eacae4e9e303e3 to your computer and use it in GitHub Desktop.
Save hugomota/946a71d28ab39985c8eacae4e9e303e3 to your computer and use it in GitHub Desktop.
CX Authentication sample as pre-request script on postman (urlencoded)
const echoPostRequest = {
url: pm.collectionVariables.get("authUrl"),
method: "POST",
header: {
"content-type": "application/x-www-form-urlencoded",
},
body: {
mode: "urlencoded",
urlencoded: [
{
key: "username",
value: pm.collectionVariables.get("username"),
disabled: false,
},
{
key: "password",
value: pm.collectionVariables.get("password"),
disabled: false,
},
{ key: "acr_values", value: pm.collectionVariables.get("acrValues"), disabled: false },
{ key: "scope", value: pm.collectionVariables.get("scope"), disabled: false },
{ key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
{ key: "grant_type", value:pm.collectionVariables.get("grantType"), disabled: false },
],
},
};
var getToken = true;
if (
!pm.collectionVariables.get("accessTokenExpiry") ||
!pm.collectionVariables.get("currentAccessToken")
) {
console.log("Token or expiry date are missing");
} else if (
pm.collectionVariables.get("accessTokenExpiry") <= new Date().getTime()
) {
console.log("Token is expired");
} else {
getToken = false;
console.log("Token and expiry date are all good");
}
if (getToken === true) {
pm.sendRequest(echoPostRequest, function (err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log("Saving the token and expiry date");
var responseJson = res.json();
pm.collectionVariables.set(
"currentAccessToken",
responseJson.access_token
);
var expiryDate = new Date();
expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
pm.collectionVariables.set("accessTokenExpiry", expiryDate.getTime());
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment