Unauthorized response using Bearer Token Authorization

  • k6 version: k6 v0.37.0 (2022-03-15T09:43:55+0000/67657f4, go1.17.7, windows/amd64)
  • OS and version: Windows 10
const BASE_URL = 'http://localhost/api/v1/';

export function setup() {
	let login_headers = {Authorization: 'Basic dHNlX2FwaaaaYXNzd29yZA=='};
	const loginRes = http.post(`${BASE_URL}login/`, {}, { headers: login_headers });

	const authToken = loginRes.json().data.accessToken;
	check(authToken, { 'logged in successfully': () => authToken !== '' });

	return authToken;
}

export default (authToken) => {
	 group('Get Accounts', () => {
      const request_headers = {
		  'content-type': "application/json",
		  'Authorization': `Bearer ${authToken}`};
	console.log("The Header: " + JSON.stringify(request_headers));
	//Get all accounts
	let res_accounts = http.get(`${BASE_URL}accounts/`, {}, {headers: request_headers});
	const message = res_accounts.json().message;
	check(message, { 'get accounts unauthorized': () => message === 'Unauthorized Token.' });
    });		
};

I checked that the console.log("The Header: " + JSON.stringify(request_headers));

The Header: {“content-type”:“application/json”,“Authorization”:“Bearer SFMyNTY.g2gDbQAAACQjUmVmPDAuMzg5MjM1NTc3OC4zNTM0MjI1NDE2LjEwMDUyNj5uBgByyaBqgAFiAAFRgA.UuIbEYbsn4ZKcqorNFnfxVlwqwJdsXGo8sDKYOmsi64”}

printed the correct header, and I also used this token and tested ok on Postman.

But when run with k6 I got the message ‘Unauthorized Token.’ due to k6 not sent the header to API server.
I traced at server then the header not included the Authorization.

headers: %{
       "host" => "localhost",
       "user-agent" => "k6/0.37.0 (https://k6.io/)"
     }

Please help to review.

After check the docs of http.get get( url, [params] ) , I found the issue and fixed.
Old:
let res_accounts = http.get(${BASE_URL}accounts/, {}, {headers: request_headers});
Fix:
let res_accounts = http.get(${BASE_URL}accounts/, {headers: request_headers});

Thanks and hope that my issue could for someone refer.

1 Like