Ziwdigforbugs
Ziwdigforbugs

Reputation: 1214

JWT token authentication with K6

I am new to K6, and I want to authenticate through a JWT token on a login endpoint. I did this first with postman and it works. However, on K6 I am getting a 401 error.

Here is my K6 code:

import http from 'k6/http';
import { sleep } from 'k6';
import { htmlReport } from "https://raw.githubusercontent.com/benc-uk/k6-reporter/main/dist/bundle.js";
import { textSummary } from "https://jslib.k6.io/k6-summary/0.0.1/index.js";
import { check } from 'k6';

export let options = {
    iterations:1,
    vus: 1,
    thresholds: {
        http_req_duration: ['avg < 500']
    }
};

export default function() {
    const URL = 'https://gateway.test.idnow.de/api/v1/*******/login'
    const APIKEY= '***************************';
    const playload = JSON.stringify({
        "apiKey": "{{APIKEY}}"
    });
    const params = {
        headers: {
            'Content-Type': 'application/json',
        },
    };
    const res = http.post(URL, playload, params, {redirects: 0});
    check(res, {
        "status code should be 200": res => res.status === 200,
    });

    sleep(1);
    console.log(`status: "${res.status}"`);
    console.log(`body full: ${res.body}`);
};

export function handleSummary(data) {
    return {
        "scriptReport.html": htmlReport(data),
        stdout: textSummary(data, { indent: "", enableColors: true })
    };
}

Here is the result:

running (00m01.0s), 1/1 VUs, 0 complete and 0 interrupted iterations
default   [   0% ] 1 VUs  00m01.0s/10m0s  0/1 shared iters
time="2022-09-10T14:54:25Z" level=info msg="Response:\nHTTP/2.0 401 Unauthorized\nContent-Length: 125\nAccess-Control-Allow-Origin: *\nContent-Type: application/json; charset=UTF-8\nDate: Sat, 10 Sep 2022 14:54:25 GMT\nStrict-Transport-Security: max-age=16000000;\n\n\n" group= iter=0 request_id=2538f2ba-b3b9-4c88-584d-59e343835906 scenario=default source=http-debug vu=1

running (00m02.0s), 1/1 VUs, 0 complete and 0 interrupted iterations
default   [   0% ] 1 VUs  00m02.0s/10m0s  0/1 shared iters
time="2022-09-10T14:54:26Z" level=info msg="status: \"401\"" source=console
time="2022-09-10T14:54:26Z" level=info msg="body full: {\"errors\":[{\"cause\":\"INVALID_LOGIN_TOKEN\",\"errorType\":null,\"id\":\"70470303\",\"key\":null,\"message\":null,\"translationKey\":null}]}" source=console

I am surprised to see that the error is returning INVALID_LOGIN_TOKEN when this API should simply return a token.

Upvotes: 2

Views: 1650

Answers (1)

knittl
knittl

Reputation: 265201

const APIKEY= '***************************';
const payload = JSON.stringify({
    "apiKey": "{{APIKEY}}"
  });

Will try to login with the literal value {{APIKEY}}. I don't know where you got the idea, but k6 does not support handlebars or mustache templates.

k6 scripts are JavaScript. The APIKEY is a variable (actually a constant) which will be automatically dereferenced and replaced with its value. No need for string interpolation or template engines.

const APIKEY= '***************************';
const payload = JSON.stringify({
    "apiKey": APIKEY
  });

If you must, you could use template strings, which was probably the intention behind using the mustache syntax (but why bother if the constant can be used directly):

const APIKEY= '***************************';
const payload = JSON.stringify({
    "apiKey": `${APIKEY}`
  });

To confirm, you can simply print the content of your payload as part of your script:

console.log(payload);

PS. It's payload, not playload.

Upvotes: 2

Related Questions