You need to create a variable called token. To use it in a request, you need to save it as a collection or environment variable (I recommend an environment variable).
If you want to work it with any request, then the best option is a pre-request script that checks the expiry date of the token.
The following is an example of authenticating to Azure Key Vault that you can use as a baseline.
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
pm.test("Pre-request check for Environment Variables", function () {
let vars = ['client_id', 'scope', 'tenant_id', 'client_secret', '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("tenant_id") + '/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("client_id"), disabled: false },
{ key: "scope", value: pm.environment.get("scope"), disabled: false },
{ key: "client_secret", value: pm.environment.get("client_secret"), disabled: false },
{ key: "grant_type", value: "client_credentials", 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);
let token = resJson.access_token;
// console.log(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);
// console.log(decoded);
let expiryDate = new Date(decoded.exp * 1000);
// console.log(expiryDate);
pm.environment.set("bearerToken", token);
pm.environment.set("bearerTokenExpiresOn", expiryDate);
// console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
});
}
});
});
};
This is another example where the API also includes an expiry date, so you don’t need to pull apart the token to get the date.
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', 'testaccount_one_name', 'testaccount_one_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("testaccount_one_name"), disabled: false },
{ key: "password", value: pm.environment.get("testaccount_one_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"));
});
}
});
});
};
You need to test the expiration as I found that API’s return vastly different date formats. Yours might be slightly different to the two examples shown above. The two example are both using Microsoft, but different services, and one service returns a date in the response, and the other does not (Hence you need to test that its actually working).
You need to update the request so it matches the authentication for your API. Client Credentials, Password, etc. This won’t work with API’s that use the authentication_code grant, as that requires browser\user interaction.
The above requires a base level understanding of JavaScript.