Run a POST request to fetch an access_token only once and use it in another POST call multiple times

Dear All,

I have a following requirement:
I have 2 POST requests, where first will give the access_token and I need to use this access_token in the next POST call.

  • Call a POST request and fetch the access_token (this call should only be once, because the token is valid for next 30 mins and need not to be called again)
  • Store it in a global variable
  • Call another POST with the fetched access_token and run this request for multiple users

I am new to K6 and this might be like a very beginner code, please guide me how can I achieve this.
Thanks in advance!

import http from 'k6/http';
import { sleep } from 'k6';
let bearerToken;

export default function () {

    const url = "https://xxxx.xxxx.com/xxxx/xxxx/v1/token?companyId=xxxx-xxxx";

    const respToken = http.post(url, { 'grant_type': 'client_credentials', 'scope': 'xxxx'}, {
        headers: { 'X-xxxx-Context': 'companyId', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Basic xxxx==' },
    });
    if (respToken.status === 200) {
        console.log('Request succeeded!');
        console.log(respToken.status);
        const responseJson = JSON.parse(respToken.body);
        bearerToken = "Bearer " + responseJson.access_token;
        console.log("!!!!!bearerToken: " + bearerToken);
    } else {
        console.error('Request failed with status code: ' + respToken.status + ' ' + respToken.body);
    }

    sleep(1);

    const urlService = "https://api-xxx.xxxx.com/xxxx/applications";
    let headers = { headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": bearerToken}}

    let rawBody = JSON.stringify({
        "countryCode": "ES",
        "companyId": "xxxx",
        "channel": "",
        "onboardingProductType": "xxxx"
    });

    const resp = http.post(urlService, rawBody, headers);

    if (resp.status === 201) {
        console.log('Request succeeded!');
    } else {
        console.error('Request failed with status code: ' + resp.status);
    }

    sleep(1);
}

I have found the solution:

import http from 'k6/http';
import { sleep } from 'k6';
let bearerToken;

export function setup() {
    const url = "https://xxx-xx.xx.com/oauth2/xx/v1/token?companyId=xxxx-xxxx";

    const respToken = http.post(url, { 'grant_type': 'client_credentials', 'scope': 'xxx'}, {
        headers: { 'X-xx-Context': 'companyId', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'Authorization': 'Basic xxxx==' },
    });
    if (respToken.status === 200) {
        console.log('Request succeeded!');
        console.log(respToken.status);
        const responseJson = JSON.parse(respToken.body);
        bearerToken = "Bearer " + responseJson.access_token;
        console.log("!!!!!bearerToken: " + bearerToken);
    } else {
        console.error('Request failed with status code: ' + respToken.status + ' ' + respToken.body);
    }

    return { bearerToken: bearerToken };
}

export const options = {
    scenarios: {
        firstScenario: {
            executor: "shared-iterations",
            vus: 10,
            iterations: 10
        }
    }
}

export default function (data) {

    const urlService = "https://api-xxx.xxx.com/xxx/applications";
    let headers = { headers: { "Accept": "application/json", "Content-Type": "application/json", "Authorization": data.bearerToken}}

    let rawBody = JSON.stringify({
        "countryCode": "ES",
        "companyId": "xxx-xxx",
        "channel": "",
        "onboardingProductType": "xxx"
    });

    const resp = http.post(urlService, rawBody, headers);
    if (resp.status === 201) {
        console.log('Request succeeded!');
    } else {
        console.error('Request failed with status code: ' + resp.status);
    }

    sleep(1);
}
3 Likes

I use bash script and a curl request and pass it in as a variable. Have you thought about each user needing their own bearer tokens. it is possible to achieve this also with a little configuration.

Thanks Jamie for your suggestion, I am good for now :slight_smile: