Generated Token every 10 mins and use it during load test

Hello All,
I am having a same issue, our token expires in 1hr. following code is working for me.

Steps to resolve:

  • in your setup create a empty token stub
export async function setup() {       
    let tokenData = {
        token: undefined,
        expiresAt: new Date().getTime() + (2 * 1000),
        expiresDuration: 2
    };
    return tokenData;
}
  • In your default function, get the tokenData, verify the expiresTime. if it is expired, generate again.else return the same tokenData.
export default async function (tokenData) {    
    tokenData = await accessToken(tokenData);
    await authz(tokenData.token);
}
async function accessTokenFromTid(tokenData) {
    if(tokenData && tokenData.token && new Date(tokenData.expiresAt) > new Date().getTime()) {
        return tokenData;
    } else {
        console.log(`Refreshing token`);
        const url = 'https://jayanth.com/oauth/token';
        let payload = {
            'grant_type': 'client_credentials',
            'scope': 'Tam-Test-Jai',
        };
        let headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + encoding.b64encode("xxxxxxx:xxxxxxxx"),
        };
        //console.log(`Requesting access token from ${url} with payload ${JSON.stringify(payload)} and headers ${JSON.stringify(headers)}`);
        let res = await http.post(url, payload, { headers: headers});    
        if (res.status != 200) {
            console.error(res.body);
            throw new Error(`Request failed with status: ${res.status}`);
        }
        tokenData.token = res.json().access_token;
        return tokenData;
    }
    
}

final output : every 2 seconds, refreshing token is executing.

1 Like