This example demonstrates how to create new users or login existing users with AWS Cognito 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
AWS_ACCESS_KEY_ID=YOUR_KEY_ID
AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY
AWS_REGION=us-west-2
USER_POOL_ID=YOUR_USER_POOL_ID
CLIENT_ID=YOUR_COGNITO_CLIENT_ID
GENERIC_PASSWORD=1234567890!!!!AAAaaa
API_BASE_URL=https://example.api.tld
Test Spec
import {
  CognitoIdentityProviderClient,
  AdminCreateUserCommand,
  AdminInitiateAuthCommand,
  AdminSetUserPasswordCommand,
} from '@aws-sdk/client-cognito-identity-provider';
import axios from 'axios';

class CognitoTestSpec {
  npmDeps = {
    '@aws-sdk/client-cognito-identity-provider': '3.465.0',
    axios: '1.6.0',
  };

  async vuInit(ctx) {
    // Create an AWS Cognito client
    const cognitoClient = new CognitoIdentityProviderClient({
      credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID,
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
      },
      region: process.env.AWS_REGION,
    });

    // 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 cognitoClient
      .send(
        new AdminCreateUserCommand({
          UserPoolId: process.env.USER_POOL_ID,
          Username: username,
          MessageAction: 'SUPPRESS',
          UserAttributes: [
            { Name: 'email', Value: email },
            { Name: 'email_verified', Value: 'true' },
          ],
        }),
      )
      .catch(() => null);

    // Set password for the user
    await cognitoClient.send(
      new AdminSetUserPasswordCommand({
        UserPoolId: process.env.USER_POOL_ID,
        Username: username,
        Password: process.env.GENERIC_PASSWORD,
        Permanent: true,
      }),
    );

    // Log the user in to get an access token
    const authResult = await cognitoClient.send(
      new AdminInitiateAuthCommand({
        UserPoolId: process.env.USER_POOL_ID,
        ClientId: process.env.CLIENT_ID,
        AuthFlow: 'ADMIN_USER_PASSWORD_AUTH',
        AuthParameters: {
          USERNAME: username,
          PASSWORD: process.env.GENERIC_PASSWORD,
        },
      }),
    );

    const jwt = authResult.AuthenticationResult.AccessToken;

    // Debug Run log to check that we are logging in successfully
    console.debug('JWT: ', jwt);

    // 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 scripts here
  }
}