This example demonstrates how to create new users or login existing users with Auth0 during a load test. During the vuInit() stage of the load test, a new user is created and logged in to obtain an access token. Each user is created with a username and password, rather than social logins or OAuth. If a user already exists, we just log them in. Then, during the vuLoop() stage of the load test, a new axios instance is created using the user’s access toke, and used to make requests against our API.

Prerequisites

Code

Environment Variables
AUTH0_DOMAIN=your-domain.auth0.com
AUTH0_CLIENT_ID=YOUR_CLIENT_ID
AUTH0_CLIENT_SECRET=YOUR_CLIENT_SECRET
AUTH0_AUDIENCE=https://example.api.tld
AUTH0_CONNECTION=Username-Password-Authentication
GENERIC_PASSWORD=1234567890!!!!AAAaaa
API_BASE_URL=https://example.api.tld
Test Spec
import auth0 from 'auth0';
import axios from 'axios';

class Auth0TestSpec {
  npmDeps = {
    auth0: '4.1.0',
    axios: '1.6.0',
  };

  async vuInit(ctx) {
    // Create an Auth0 client
    const auth0Client = new auth0.AuthenticationClient({
      domain: process.env.AUTH0_DOMAIN,
      clientId: process.env.AUTH0_CLIENT_ID,
      clientSecret: process.env.AUTH0_CLIENT_SECRET,
    });

    // Generate a unique username, with the Virtual User's id
    const username = `user${ctx.info.vuId}`;
    const email = `${username}@example.tld`;

    // Attempt to sign up the user and fail silently, in case they already exist
    await auth0Client.database
      .signUp({
        email,
        password: process.env.GENERIC_PASSWORD,
        connection: process.env.AUTH0_CONNECTION,
        username,
      })
      .catch(() => null);

    // Log the user in to get an access token
    const authResult = await auth0Client.oauth.passwordGrant({
      audience: process.env.AUTH0_AUDIENCE,
      username: email,
      password: process.env.GENERIC_PASSWORD,
    });

    // Debug Run log to check that we are logging in successfully
    console.debug(authResult.data);

    const jwt = authResult.data.access_token;

    // Create an axios instance with the access token as a bearer token
    const apiClient = axios.create({
      baseURL: process.env.API_BASE_URL,
      headers: { Authorization: `Bearer ${jwt}` },
    });

    // Pass the axios instance down to the vuLoop() stage
    return { apiClient };
  }

  async vuLoop(ctx) {
    const { apiClient } = ctx.vuInitData;

    // Now we can make authenticated requests to our API 🎉
    // Example: const response = await apiClient.get('user');
    // Insert the rest of your load test here
  }
}