Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Protocols and APIs

Authentication, Tokens and Correlation in k6

Log in once in setup or per iteration, pass bearer tokens, refresh expiring tokens, and correlate dynamic values such as CSRF tokens and ids between requests in k6 scripts.

Realistic user journeys are full of values that the server invents: session ids, CSRF tokens, order numbers, JWTs. A script that hard-codes yesterday's token will fail today. Correlation means extracting such a value from one response and sending it in the next request. Authentication is the most common case, and it raises a design question: who logs in, and how often?

Honesty note. k6 cannot run here. k6/http code is read-only; the runnable blocks are Node stand-ins that reproduce the flow against a local server. Never put real credentials in scripts: use environment variables (__ENV.API_USER) and k6's -e flag.

Three login strategies

Strategy How Good for Watch out
Log in once in setup() One token shared by all VUs API tests where the login is not what you measure Token may expire; all VUs share one identity
Log in per VU (first iteration) Store the token in a VU-level variable Realistic long-lived users Needs a distinct user per VU
Log in every iteration Part of the journey Measuring the login endpoint itself Adds login load to every iteration

Pick on purpose. If login is expensive (password hashing is designed to be), logging in every iteration can become the test.

Login in setup

setup() runs once before the load starts; whatever it returns is passed to default and teardown as a copy:

JavaScript
import http from 'k6/http';
import { check } from 'k6';

export function setup() {
  const res = http.post(
    `${__ENV.BASE_URL}/api/login`,
    JSON.stringify({ user: __ENV.API_USER, pass: __ENV.API_PASS }),
    { headers: { 'Content-Type': 'application/json' } },
  );
  check(res, { 'login ok': (r) => r.status === 200 });
  return { token: res.json('token') };
}

export default function (data) {
  const params = { headers: { Authorization: `Bearer ${data.token}` } };
  http.get(`${__ENV.BASE_URL}/api/orders`, params);
}

Run it with k6 run -e BASE_URL=https://staging.example.test -e API_USER=loadtest -e API_PASS=... script.js. Because the data is serialized between stages, you can return numbers, strings, arrays and plain objects, but not functions.

Per-VU tokens and refresh

Variables declared at the top level are initialized once per VU, so a VU can keep its own token between iterations:

JavaScript
let token = null;
let expiresAt = 0;

function ensureToken() {
  if (token && Date.now() < expiresAt - 30_000) return; // refresh 30 s early
  const res = http.post(`${BASE}/api/login`, JSON.stringify(creds()), JSON_HEADERS);
  token = res.json('token');
  expiresAt = Date.now() + res.json('expires_in') * 1000;
}

export default function () {
  ensureToken();
  http.get(`${BASE}/api/orders`, { headers: { Authorization: `Bearer ${token}` } });
}

Refreshing slightly before expiry is the same strategy a well-written client uses, and it prevents bursts of 401 responses at expiry time. To give each VU its own account, pick credentials by __VU (the VU number, starting at 1) from a data file; see Data and shared files.

Node.js Stand-in: login once, then reuse a bearer token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Correlation: extracting dynamic values

Correlation has three steps: request, extract, reuse. k6 gives you several ways to extract:

  • res.json('data.id'): JSON by path.
  • res.html().find('input[name=csrf]').attr('value'): parse HTML with a jQuery-like API.
  • res.headers['Location'], res.cookies: headers and cookies.
  • res.body.match(/regex/): the fallback when nothing else fits.

A CSRF-protected form flow looks like this:

JavaScript
import http from 'k6/http';
import { check, fail } from 'k6';

export default function () {
  const page = http.get(`${BASE}/signup`);
  const csrf = page.html().find('input[name=csrf]').first().attr('value');
  if (!csrf) fail('no CSRF token found: page layout changed?');

  const res = http.post(`${BASE}/signup`, { email: `u${__VU}-${__ITER}@example.test`, csrf });
  check(res, { 'account created': (r) => r.status === 201 || r.status === 302 });
}

fail() aborts the current iteration with a clear message and counts it as a failed iteration, which is much better than sending undefined to the server and getting a confusing 403.

Notice the unique email built from __VU and __ITER: tests that create data need values that do not collide across VUs.

Node.js Stand-in: extracting a CSRF token from HTML and a created id from JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Other authentication styles

  • Basic auth: put the credentials in the URL (https://user:pass@host/) and k6 sends them as Basic, or set the Authorization header yourself. The request param auth: 'digest' or auth: 'ntlm' selects those schemes.
  • API keys: a header such as X-API-Key taken from __ENV.
  • OAuth2 client credentials: one POST to the token endpoint in setup(), then the bearer header. For authorization-code flows with a browser redirect, test the API with a pre-issued token instead of load-testing the identity provider (which you may not own).
  • Signed requests (HMAC): import { hmac } from 'k6/crypto' can build signatures. Keep the signing key in an environment variable, and see Test design and workload models for how login fits into a journey.

Pitfalls

  1. Load testing a third-party identity provider by accident. Get permission first.
  2. Sharing one user for every VU when the application locks sessions or limits concurrent logins.
  3. Forgetting that tokens expire during long soak tests.
  4. Printing tokens to the console in CI logs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is correlation in a load test?

    Correlation handles server-generated values such as tokens, CSRF fields and ids, so each request carries a valid, current value.
  2. 2. What does setup() return value get passed to?

    k6 serializes the data returned by setup() and passes a copy to every VU's default function and to teardown().
  3. 3. Why refresh a token shortly before it expires?

    Real clients refresh early; doing so keeps long tests from failing in waves when many VUs hit expiry together.
  4. 4. What does fail('message') do in a k6 script?

    fail() raises an error that ends the current iteration with a message, which is clearer than sending bad data onward.

Summary

  • Choose a login strategy deliberately: setup, per VU or per iteration.
  • Read credentials from __ENV, never from the source file.
  • Correlate with res.json(), res.html(), headers or regex, and fail() when the value is missing.
  • Make created data unique with __VU and __ITER.

Next: Browser Testing with k6