You can also use a pre-request script which will allow you more options with what you can do with the response.
You can also use the expiry dates so that you aren’t getting a new token each and every time.
Here is an example of authenticating to Microsoft that you can use as a starter for 10.
let currentDateTime = Date.now();
let tokenExpiry = pm.environment.get("bearerTokenExpiresOn")
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
pm.test("Pre-request check for Environment Variables", function () {
let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
vars.forEach(function (item) {
// console.log(item);
pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
});
pm.sendRequest({
url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/token',
method: 'POST',
header: 'Content-Type: application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "client_id", value: pm.environment.get("clientId"), disabled: false },
{ key: "scope", value: pm.environment.get("scope"), disabled: false },
{ key: "username", value: pm.environment.get("username"), disabled: false },
{ key: "password", value: pm.environment.get("password"), disabled: false },
{ key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false },
{ key: "grant_type", value: "password", disabled: false },
]
}
}, function (err, res) {
if (err) {
console.log(err);
} else {
pm.test("Pre-request Microsoft login Status code is 200", () => {
pm.expect(res).to.have.status(200);
let resJson = res.json();
// console.log(resJson);
pm.environment.set("bearerToken", resJson.id_token);
pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
// console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
});
}
});
});
};
The following example is where the API doesn’t specifically provide you with an expiry time. The details can usually still be retreived from the actual token.
let moment = require('moment');
let currentDateTime = moment(new Date()).format("YYYYMMDDHHmmss");
let tokenExpiry = moment(pm.environment.get("tokenExpiresOn")).format("YYYYMMDDHHmmss");
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("JWT") || currentDateTime > tokenExpiry) {
pm.test("Pre-request check for required Environment Variables", function () {
let vars = ['username', 'password'];
vars.forEach(function (item) {
// console.log(item);
pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
});
pm.sendRequest({
url: 'https://' + pm.environment.get("URL") + '/thirdparty-access/v1/authenticate',
method: 'POST',
header: 'Content-Type: application/json',
body: {
mode: 'raw',
raw: JSON.stringify({ 'userName': pm.environment.get("username"), 'password': pm.environment.get("password") })
}
}, function (err, res) {
if (err) {
console.log(err);
} else {
pm.test("Pre-request Authentication Status code is 200", () => {
pm.expect(res).to.have.status(200);
let resJson = res.json();
// console.log(resJson);
let token = resJson["id-token"]
function parseJwt(token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
}
let decoded = parseJwt(token);
let expiryDate = new Date(decoded.exp * 1000);
pm.environment.set("tokenExpiresOn", expiryDate);
pm.environment.set("JWT", token);
// console.log("Token ExpiresOn: " + pm.environment.get("tokenExpiresOn"));
});
}
});
});
};