Basic Authentication Using K6

Sometimes when you are load testing you api endpoint you may need to pass basic auth credentials. In this tutorial we will learn how to send basic auth using k6.

Use following code to send basic authentication using k6:

import http from 'k6/http';
import encoding from 'k6/encoding';

export default function () {

  // send custom payload/post data
  const payload = JSON.stringify({
      email: 'aaa',
      password: 'bbb',
  });

  // encrypt your credentials in base64 format
  const encodedCredentials = encoding.b64encode("username:password");

 // send post request with custom header and payload
  http.post('http://some-api-url/endpoint', payload, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Basic ${encodedCredentials}`,
    },
  });
}

As you can see in this example you need to import encoding module from k6. Then use  b64encode function to encrypt your username and password joined with colon(:).

Then you need to use Authorization header and put your encoded credentials using word Basic and a space in between.

Now, run above script to see the results on your terminal:

k6 run test.js