Using Auth0 authentication

We currently use Auth0 to verify that we have permission to access our API,however we’ve found that if we call it from the default function then Auth0 gets called over and over again and gets very upset.

So I’ve tried to put it into the Setup function and I can see it calling Auth0 and it retrieving the token but when I then try to assign that token to a global variable and use it to set the Auth header in the calls to our service, it’s undefined.

This is my setup function:

let externalIdentityToken; //this is set up at the top of the function with all the k6 variables

export function setup() {
    let auth0Request = JSON.stringify({
        client_id: environment.Auth0TestAppClientId,
        client_secret: environment.Auth0TestAppClientSecret,
        scope: environment.Auth0TestAppScope,
        username: environment.Auth0TestAccountUsername,
        password: environment.Auth0TestAccountPassword,
        grant_type: environment.Auth0TestAccountGrantType,
        realm: environment.Auth0Realm,
    });

    let url = `${environment.Auth0Domain}/oauth/token`;

    let params = {
        headers: {
            "Content-Type": "application/json",
        },
    };

    let response = http.post(url, auth0Request, params);

    externalIdentityToken = response.json().id_token;

    //console.log(JSON.stringify(externalIdentityToken));
}

However as soon as you use that variable within the default function, it’s undefined.

Is this the correct way to setup something I need to use repeatedly later on or is there a better way?

Hi @joanne.ainscough,
The setup and the default function aren’t ran in the same JS VM. This obviously won’t work with multiple VUs as they are different JS VMs and setup is ran only once per the whole test.

This means that any “global” variable is only global for the current VU.

The simplest fix for what you want is to use the fact that setup can return data to the default function(s) (and teardown). There is are two examples in the documentation about setup and teardown.

Arguably, though, there should be a token per VU and it probably has an expiration time, so it might just be better to make your own http.request function that adds the token and regets it every once in a while ( for example on 401s or just before it expires).

Hope this helps