OAuth2 Mock Server

8.2.2 · active · verified Sun Apr 19

oauth2-mock-server is a JavaScript/TypeScript library designed to provide a configurable OAuth2/OpenID Connect server for automated testing and development purposes. It allows developers to simulate an OAuth2 provider to issue verifiable access tokens without needing a full-fledged identity provider, making it ideal for unit and integration tests. The library supports various OAuth2 grant types, including Client Credentials, Resource Owner Password Credentials, Authorization Code (with PKCE), and Refresh Token grants. It also supports multiple JWK formats for signing tokens (RSA, EC, EdDSA). The current stable version is 8.2.2, with recent releases indicating an active maintenance and development cadence focused on dependency updates, minor feature additions, and bug fixes. A key differentiator is its programmatic control via event emitters for customizing server behavior, allowing for specific test scenarios, such as modifying token expiration or adding custom claims. It is explicitly not intended for production use due to a lack of full feature parity and security hardening.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize, configure, and operate the `oauth2-mock-server`. It shows how to generate cryptographic keys, start the server on a dynamic port, build JWTs programmatically, and apply customization hooks to modify token claims before signing, simulating an OAuth2 flow for testing purposes.

import { OAuth2Server } from 'oauth2-mock-server';
import axios from 'axios';

async function runMockServerExample() {
  let server = new OAuth2Server();

  // Generate a new RSA key and add it to the keystore
  await server.issuer.keys.generate('RS256');

  // Start the server on a free port, typically a high port for testing
  // using 0 lets the OS pick a free port, then get the port from server.port
  await server.start(0, 'localhost');
  const port = server.port;
  console.log('Mock OAuth2 Server started on port:', port);
  console.log('Issuer URL:', server.issuer.url); // -> http://localhost:PORT

  // --- Example: Build a token and use it ---
  try {
    let token = await server.issuer.buildToken();
    console.log('Generated JWT:', token);

    // Call a remote API with the token (this part won't actually work without a real API)
    // For demonstration, let's just log what would happen
    const exampleApiUrl = 'https://api.example.com/secure-data';
    console.log(`Attempting to call ${exampleApiUrl} with Bearer token...`);
    // In a real test, you'd point this to your application's protected endpoint
    // and your application would validate this token against the mock server's JWKS endpoint.

    // const response = await axios.get(exampleApiUrl, {
    //   headers: {
    //     authorization: `Bearer ${token}`,
    //   },
    // });
    // console.log('API Response (simulated):', response.data);

    // --- Example: Customize next token signing ---
    server.once('beforeTokenSigning', (modifiedToken) => {
      console.log('Modifying next token: Adding custom claim "test_claim".');
      modifiedToken.payload.test_claim = 'custom_value';
      modifiedToken.payload.exp = Math.floor(Date.now() / 1000) + 60; // Make it expire in 60s
    });

    let customToken = await server.issuer.buildToken();
    console.log('Generated custom JWT:', customToken);
    // You would typically decode and assert properties of customToken here in a test.

  } catch (error) {
    console.error('Error during mock server operation:', error);
  } finally {
    // Stop the server
    console.log('Stopping mock server...');
    await server.stop();
    console.log('Mock server stopped.');
  }
}

runMockServerExample();

view raw JSON →