How do I obtain the bearer token from the authorization header of a webpage that I want to check in k6?

I’m trying to perform a test on a URL but I require a bearer token to do so. I found out while using the k6 browser recording tool, it automatically took the bearer token from the authorization header and used it in the code.

How do I obtain the bearer token from the website so that I can store it as a variable that I can use in other places as well?

My code is shown below:

I’ve been trying to find the answer all day but nothing seems to work.

Hi there! What you are describing is called Data Correlation and it can be quite challenging if you’re new to reverse-engineering HTTP :wink:

The Authorization header value (aka token) is typically received from an earlier request’s response. You’ll need to figure out where it is, and then write some code that interacts with the res.body to extract it.

A generic way of performing extracts regardless of the Content-Type of the response would be to use findBetween, which allows you to specify the string that should precede the value you want to extract as well as the one immediately after it.

For example, say that the token appears like this in some HTML:

<input type="hidden" name="token" value="eyJhbGci0i...."</input>

You could extract it with this code:

// at the top of your script:
import { findBetween } from 'https://jslib.k6.io/k6-utils/1.2.0/index.js';

// later, after sending the request that contains the token in the response:
let res = http.get("https://your.url");

const token = findBetween(res.body, 'name="token" value="', '"</input>"'); // note the use of single-quotes around the strings

// for debugging:
console.log('Extracted token: ' + token);

The tricky part will be finding where the token came from. My favored approach is to use a Web Debugging Proxy that is able to capture HTTP traffic when you’re interacting with your API/website. With it, you can compare what happens in the browser with what your script is doing and that should make finding tokens and other values much easier. I’ve described the process in this blog post.

In my case the token is not stored in an input field or in any HTML tag. It’s a JSON object that I can see in the local storage using developer tools. I just want to obtain that and store it in a variable.

The server will have sent the token at some point. Make sure you are recording from an Incognito session, i.e. one where you are not already logged in (and therefore the local storage should be empty).