For the past two months, I have been exploring API and software testing, and I can tell you it hasn’t been easy for me. I always thought, “Isn’t it just testing?” but I was wrong. Testing is about ensuring the application works as expected and identifying any vulnerabilities or issues within it.
Recently, I have been overwhelmed by copying IDs from one endpoint to another because the testing had to be done manually. One of the challenges is copying the bearer token and saving it.
Not-so-fun fact: This bearer token expires every 15 minutes.
I won’t lie; it’s exhausting and frustrating. Then today, something changed when a developer told me, “You should find a way for the bearer token to be generated automatically so you don’t have to go through the stress of copying the token every time.”
At first, it seemed impossible, but then I sat down, and after two hours with ChatGPT, I was able to create a script that automates this process for me.
The Automation Script and Breakdown
:::info
Note: This script is only for the Postman collection
:::
-
In your environment, create the following variable and leave it empty:
I.
bearerToken
ii.
token_expiry
iii.
refreshToken
if any necessary -
In your collection, add the following script to the
Pre-req
:
// Base URL and path variables (replace with your own API details)
let baseUrl = pm.variables.get("baseUrl");
let parameter1 = pm.variables.get("parameter1");
let parameter2 = pm.variables.get("parameter2");
// Current timestamp
let now = Math.floor(Date.now() / 1000);
// --- Function: Login with username + password ---
function loginWithCredentials() {
let loginUrl = `${baseUrl}/${parameter1}/${parameter2}/Auth/token`;
pm.sendRequest({
url: loginUrl,
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify({
// if the endpoint uses a body parameter pass it like this:
username: pm.variables.get("username"), // from Postman environment
password: pm.variables.get("password") // from Postman environment
})
}
}, function (err, res) {
if (!err && res.code === 200) {
let data = res.json();
// Store tokens + expiry time in Postman environment
pm.environment.set("bearerToken", data.token);
pm.environment.set("refreshToken", data.refreshToken);
pm.environment.set("token_expiry", now + 900); // adjust according to your API
console.log("Logged in successfully!");
} else {
console.error("Login failed:", err || res.text());
}
});
}
// --- Function: Refresh token ---
function refreshAccessToken(refreshToken) {
let refreshUrl = `${baseUrl}/${parameter1}/${parameter1}/Auth/refresh-token`;
pm.sendRequest({
url: refreshUrl,
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify({
//if the refresh-token endpoint uses the previous token and refreshToken
token: token,
refreshToken: refreshToken
})
}
}, function (err, res) {
if (!err && res.code === 200) {
let data = res.json();
pm.environment.set("bearerToken", data.token);
pm.environment.set("refreshToken", data.refreshToken || refreshToken);
pm.environment.set("token_expiry", now + 900);
console.log("Token refreshed successfully!");
} else {
console.log("Refresh failed. Falling back to login...");
loginWithCredentials();
}
});
}
// --- Token handling logic ---
let bearerToken = pm.environment.get("bearerToken");
let refreshToken = pm.environment.get("refreshToken");
let tokenExpiry = pm.environment.get("token_expiry");
if (!bearerToken || now >= tokenExpiry) {
console.log("Token expired or missing...");
if (refreshToken) {
refreshAccessToken(bearerToken, refreshToken);
} else {
loginWithCredentials();
}
} else {
console.log("Token still valid.");
}
-
With this simple, yet powerful script, I don’t have to generate tokens by myself when testing.
Here is a live action look:
:::info
Note: modify this script based on your endpoints. This means your Auth endpoint may not need a path parameter to generate a bearer token or vice-versa.
:::
I hope you find this useful. Like, share, and follow for more.