Periodically refreshing a token aside a script

Hi everyone,

I’ve the following issue : I’m currently scripting a user journey. The authentication needs to be refreshed every 5 seconds while I’m running my test.

In other load testing tools I would have use a while loop inside a fork but here, I don’t even see a correct solution.

has anyone already faced this problem ? How did you solved it ?

Thanks in advance !

Hi @camillegr,
welcome to the community forum :tada:

If you can use a dedicated token per VU then you can check the time elapsed from the last refresh and execute a new one after 5 seconds.

var refreshed = 0;

export default function() {
	var diff = new Date() - refreshed 
	if (diff > 4999) {
		console.log(`refresh the token`)
		refreshed = new Date()
	}
}

Even better if you create an HTTP wrapper where this logic is executed before each request so the code will be cleaner.

When the PR for #882 will be merged then a setTimeout could be a valid alternative. You can subscribe to it to know when it will be available.

2 Likes

Hi @codebien,

I think the http wrapper is a good solution. I’ll take a look at it.

thanks for your answer !

in my scenario, i want to generate a token and use it for 10 mins (validity ) Please help me to understand more about this logic, Where should we add this code, should we add this to generate token API or before using a token

my scenario looks like
import { group } from ‘k6’;
import {check , sleep} from ‘k6’;
import http from ‘k6/http’;
import { htmlReport } from “K6 Load Test: <%= title %>”;
import { textSummary } from ‘https://jslib.k6.io/k6-summary/0.0.1/index.js
import { SharedArray } from “k6/data”;
import papaparse from “https://jslib.k6.io/papaparse/5.1.1/index.js”;
import encoding from ‘k6/encoding’;
import { findBetween } from ‘https://jslib.k6.io/k6-utils/1.2.0/index.js’;

export const options = {

scenarios: {
setup: { // some arbitrary scenario name for genarate token
executor: ‘per-vu-iterations’,
vus: 1,
//duration: ‘1s’,
iterations: 2,
gracefulStop: ‘0s’, // do not wait for iterations to finish in the end
tags: { test_type: ‘setup’ }, // extra tags for the metrics generated by this scenario
exec: ‘setup’, // the function this scenario will execute
},
scenario1: { // some arbitrary scenario name
executor: ‘constant-vus’,
//executor: ‘per-vu-iterations’,
vus: 15,
duration: ‘60m’,
//iterations: 10,
gracefulStop: ‘0s’, // do not wait for iterations to finish in the end
tags: { test_type: ‘scenario1’ }, // extra tags for the metrics generated by this scenario
exec: ‘scenario1’, // the function this scenario will execute
},
scenario2: { // some arbitrary scenario name
executor: ‘constant-vus’,
//executor: ‘per-vu-iterations’,
vus: 15,
duration: ‘60m’,
//iterations: 10,
gracefulStop: ‘0s’, // do not wait for iterations to finish in the end
tags: { test_type: ‘scenario2’ }, // extra tags for the metrics generated by this scenario
exec: ‘scenario2’, // the function this scenario will execute
},

},
discardResponseBodies: false,
thresholds: {
// we can set different thresholds for the different scenarios because
// of the extra metric tags we set!
‘http_req_duration{test_type:api}’: [‘p(95)<250’, ‘p(99)<350’],
‘http_req_duration{test_type:website}’: [‘p(99)<500’],
http_req_duration: [{
threshold: ‘p(90) < 500’,
threshold: ‘p(95) < 900’,
abortOnFail: false,
}]

  // we can reference the scenario names as well
  //'http_req_duration{scenario:my_api_test_2}': ['p(99)<300'],

}

};

export function setup () { //genarating token here

var url1 = ‘token genaration url’;

const payload1 = {
[“client_id”]: “13246546”,
[“client_secret”]:“466464646”,

}
const params1 = {
headers : {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘Accept’ : ‘application/json’,
},

  tags: {
     name: 'Oauth', // first request
   },

 };

var Response1 = http.post(url1, payload1, params1, check);

// console.log(Response1.body);
// console.log(Response1.status);
// console.log(Response1);

check(url1, {
'is Auth ': (r) => Response1.status === 200,

});

let securityToken = findBetween(Response1.body, ‘“token”:"’, ‘",’);

return {securityToken};
//sleep(3600);

}

export default function (data) {
//console.log((data.securityToken));
let authToken = data.json(‘access_token’);
let securityToken = findBetween(Response1.body, ‘“token”:"’, ‘",’);
let refreshToken = findBetween(Response1.body, ‘“token”:"’, ‘",’);
console.log(refreshToken);

}

export function scenario1 (data) {

var url = ‘’;
const payload = ``;

const params = {
headers : {
‘Content-Type’ : ‘application/json’,
‘token = bearer token’ // using here

},

tags: {
   name: '231', // first request
 },

};

//console.log(payload);
const Response = http.post(url, payload, params, check);
//console.log(Response.body);
//console.log(Response.status);
//console.log(globalThis.vars [“vuAuthToken”]);
check(url, {
'123456 ': (r) => Response.status === 200,
});
sleep(0.8)
}
var refreshed = 0;

export function scenario2 (data) {
var diff = new Date() - refreshed
if (diff > 4999) {
console.log(refresh the token)
refreshed = new Date()
}
}
var url = ‘scenario2’;
const payload = ;

const params = {
headers : {
‘Content-Type’ : ‘application/json’,
‘Authorization’: Bearer token, // token using here
},

tags: {
name: ‘1313gdgd’, // first request
},

};

//console.log(payload);
const Response = http.post(url, payload, params, check);
// console.log(Response.body);
// console.log(Response.status);
console.log(data.securityToken);

check(url, {
'134654 ': (r) => Response.status === 200,
});
sleep(0.8)
}

Thanks for opening a separate thread @Sreenivas, we’ll follow up on Generated Token every 10 mins and use it during load test.

Cheers!

Hi @codebien.

Could you please elaborate with simple example how I should setTimeout to update my access token using refresh that lives 30 minutes?
For simplicity I think it would be enough just to generate new token every N minutes and share across VUs.

In my scenario I get access and refresh token in setup() section and then pass data to default function.

Hi @nktedo001,
sorry for the late response.

Generating the token in the setup function means you will have the first token shared across all VUs. Not having a token per VU may generate unexpected cases. You have to consider that each VU will be an independent runner so they will all try to renew the token when it expires. Whether this is fine or not depends on the implementation of your authentication service.

Regarding the set{Timeout/Interval}, as you probably need the same token across several iterations, it would require setting the timer in the Init context which unfortunately doesn’t support yet async functions. At the moment, the previous solution sounds still relevant for the current use case.

2 Likes

Thanks, in the end I reuse solution with refreshed timer

2 Likes

Hello All,

Solution to refresh token periodically, please refer here

1 Like