Postman Pre-request Script
Copy this to your pre-request script either in the Request call, or the Folder.
// Function to parse JWT token and extract expiration time
function parseJwt(token) {
let base64Url = token.split(".")[1];
let base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
let jsonPayload = decodeURIComponent(
atob(base64)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
})
.join(""),
);
return JSON.parse(jsonPayload);
}
// Get token and expiration time from environment variables
const storedToken = pm.environment.get("signin_token");
const tokenExpirationTime = pm.environment.get("token_expiration_time");
if (
storedToken &&
tokenExpirationTime &&
new Date().getTime() / 1000 < tokenExpirationTime
) {
// Token is not expired, use the existing token
console.log("Using existing token");
} else {
// Token is expired or not available, request a new one
const rawBody = JSON.stringify({
email: "your_email@example.com",
password: "your_password",
returnSecureToken: true,
});
pm.sendRequest(
{
url: "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={API_KEY}",
method: "POST",
body: rawBody,
},
function (err, response) {
const jsonResponse = response.json();
// Store the new token and its expiration time
if (jsonResponse.idToken) {
pm.environment.set("signin_token", jsonResponse.idToken);
const parsedToken = parseJwt(jsonResponse.idToken);
pm.environment.set("token_expiration_time", parsedToken.exp);
console.log("New token obtained and stored");
}
},
);
}
Under "Authorization" tab
Input {{signin_token}} into the Token
