Package detail

oauth2-mock-server

axa-group98.2kMIT8.1.0

OAuth 2 mock server

oauth, oauth2, oauth 2, mock

readme

oauth2-mock-server

npm package Node.js version

OAuth 2 mock server. Intended to be used for development or testing purposes.

When developing an application that exposes or consumes APIs that are secured with an OAuth 2 authorization scheme, a mechanism for issuing access tokens is needed. Frequently, a developer needs to create custom code that fakes the creation of tokens for testing purposes, and these tokens cannot be properly verified, since there is no actual entity issuing those tokens.

The purpose of this package is to provide an easily configurable OAuth 2 server, that can be set up and teared down at will, and can be programmatically run while performing automated tests.

Warning: This tool is not intended to be used as an actual production grade OAuth 2 server. It lacks many features that would be required in a proper implementation.

Development prerequisites

How to use

Installation

Add it to your Node.js project as a development dependency:

npm install --save-dev oauth2-mock-server

Quickstart

Here is an example for creating and running a server instance with a single random RSA key:

import { OAuth2Server } from 'oauth2-mock-server';
// ...or in CommonJS style:
// const { OAuth2Server } = require('oauth2-mock-server');

let server = new OAuth2Server();

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

// Start the server
await server.start(8080, 'localhost');
console.log('Issuer URL:', server.issuer.url); // -> http://localhost:8080

// Do some work with the server
// ...

// Stop the server
await server.stop();

Any number of existing JSON-formatted keys can be added to the keystore.

// Add an existing JWK key to the keystore
await server.issuer.keys.add({
  kid: 'some-key',
  alg: 'RS256',
  kty: 'RSA',
  // ...
});

JSON Web Tokens (JWT) can be built programmatically:

import axios from 'axios';

// Build a new token
let token = await server.issuer.buildToken();

// Call a remote API with the token
axios
  .get('https://server.example.com/api/endpoint', {
    headers: {
      authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    /* ... */
  })
  .catch((error) => {
    /* ... */
  });

Supported grant types

  • No authentication
  • Client Credentials grant
  • Resource Owner Password Credentials grant
  • Authorization Code grant, with Proof Key for Code Exchange (PKCE) support
  • Refresh token grant

Supported JWK formats

Algorithm kty alg
RSASSA-PKCS1-v1_5 RSA RS256, RS384, RS512
RSASSA-PSS RSA PS256, PS384, PS512
ECDSA EC ES256, ES384, ES512
EdDSA OKP Ed25519

Customization hooks

It also provides a convenient way, through event emitters, to programmatically customize the server processing. This is particularly useful when expecting the OIDC service to behave in a specific way on one single test:

  • The JWT access token

    // Modify the expiration time on next token produced
    service.once('beforeTokenSigning', (token, req) => {
      const timestamp = Math.floor(Date.now() / 1000);
      token.payload.exp = timestamp + 400;
    });
    const basicAuth = require('basic-auth');
    
    // Add the client ID to a token
    service.once('beforeTokenSigning', (token, req) => {
      const credentials = basicAuth(req);
      const clientId = credentials ? credentials.name : req.body.client_id;
      token.payload.client_id = clientId;
    });
  • The token endpoint response body and status

    // Force the oidc service to provide an invalid_grant response
    // on next call to the token endpoint
    service.once('beforeResponse', (tokenEndpointResponse, req) => {
      tokenEndpointResponse.body = {
        error: 'invalid_grant',
      };
      tokenEndpointResponse.statusCode = 400;
    });
  • The userinfo endpoint response body and status

    // Force the oidc service to provide an error
    // on next call to userinfo endpoint
    service.once('beforeUserinfo', (userInfoResponse, req) => {
      userInfoResponse.body = {
        error: 'invalid_token',
        error_message: 'token is expired',
      };
      userInfoResponse.statusCode = 401;
    });
  • The revoke endpoint response body and status

    // Simulates a custom token revocation body
    service.once('beforeRevoke', (revokeResponse, req) => {
      revokeResponse.body = {
        result: 'revoked',
      };
    });
  • The authorization endpoint redirect uri and query parameters

    // Modify the uri and query parameters
    // before the authorization redirect
    service.once('beforeAuthorizeRedirect', (authorizeRedirectUri, req) => {
      authorizeRedirectUri.url.searchParams.set('foo', 'bar');
    });
  • The end session endpoint post logout redirect uri

    // Modify the uri and query parameters
    // before the post_logout_redirect_uri redirect
    service.once('beforePostLogoutRedirect', (postLogoutRedirectUri, req) => {
      postLogoutRedirectUri.url.searchParams.set('foo', 'bar');
    });
  • The introspect endpoint response body

    // Simulate a custom token introspection response body
    service.once('beforeIntrospect', (introspectResponse, req) => {
      introspectResponse.body = {
        active: true,
        scope: 'read write email',
        client_id: '<client_id>',
        username: 'dummy',
        exp: 1643712575,
      };
    });

HTTPS support

It also provides basic HTTPS support, an optional cert and key can be supplied to start the server with SSL/TLS using the in-built NodeJS HTTPS module.

We recommend using a package to create a locally trusted certificate, like mkcert.

let server = new OAuth2Server(
  'test-assets/mock-auth/key.pem',
  'test-assets/mock-auth/cert.pem'
);

NOTE: Enabling HTTPS will also update the issuer URL to reflect the current protocol.

Supported endpoints

GET /.well-known/openid-configuration

Returns the OpenID Provider Configuration Information for the server.

GET /jwks

Returns the JSON Web Key Set (JWKS) of all the keys configured in the server.

POST /token

Issues access tokens.

GET /authorize

It simulates the user authentication. It will automatically redirect to the callback endpoint sent as parameter. It currently supports only 'code' response_type.

GET /userinfo

It provides extra userinfo claims.

POST /revoke

It simulates a token revocation. This endpoint should always return 200 as stated by RFC 7009.

GET /endsession

It simulates the end session endpoint. It will automatically redirect to the post_logout_redirect_uri sent as parameter.

POST /introspect

It simulates the token introspection endpoint.

Command-Line Interface

The server can be run from the command line.

npx oauth2-mock-server --help

Attributions

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog.

8.1.0 — 2025-06-06

Added

  • Export HttpServer and OAuth2Service (reported in #344 by jraoult)

Changed

  • Update dependencies

8.0.1 — 2025-05-28

Fixed

  • Fix crash when running npx oauth2-mock-server --help (reported in #337 by robcresswell)

8.0.0 — 2025-05-18

Fixed

Changed

  • Breaking: No longer support Node.js 18
  • Switched to "Universal" ESM. CommonJS require() usage pattern still supported for Nodejs ^20.19 & ^22.12
  • Add support for Node.js 24
  • Update dependencies

7.2.1 — 2025-04-30

Fixed

  • Fix paths of well known endpoints when issuer ends with a forward slash (reported in #331 by kikisaeba)

Changed

  • Update dependencies

7.2.0 — 2024-11-25

Added

  • Include scope in token for authorization_code and refresh_token grants (by PetrasJaug)
  • Add PKCE support (by tanettrimas)

Changed

  • Update dependencies

7.1.2 — 2024-05-21

Changed

7.1.1 — 2023-10-24

Fixed

  • Be a better citizen in an ECMAScript modules world

7.1.0 — 2023-10-23

Added

  • Add support for "aud" claim in "client_credentials" grants (by kadams54)

Changed

  • Update dependencies

7.0.0 — 2023-10-04

Changed

  • Breaking: No longer support Node.js 16

6.0.1 — 2023-10-03

Security

6.0.0 — 2023-06-19

Changed

  • Breaking: No longer support Node.js 14
  • Fix authorize endpoint compliance (remove scope requirement, make state optional) (by jirutka)
  • Add support for Node.js 20
  • Update dependencies

5.0.2 — 2023-02-20

Security

5.0.1 — 2022-10-04

Security

5.0.0 — 2022-06-27

Changed

  • Breaking: No longer support Node.js 12
  • Add support for Node.js 18

4.3.2 — 2022-06-27

Changed

  • Update dependencies

4.3.1 — 2022-03-29

Security

4.3.0 — 2022-02-01

Added

  • Support the token introspection endpoint (by cfman)

4.2.0 — 2022-01-28

Added

  • Add support for custom endpoint pathnames (by roskh)
  • Teach /token endpoint to support JSON content type (by roskh)

4.1.1 — 2021-11-18

Fixed

  • Fix regression: Prevent unhandled rejected promises when incorrectly invoking the /token endpoint

4.1.0 — 2021-11-15

Added

4.0.0 — 2021-10-25

Added

  • Add /endsession endpoint (by AndTem)
  • Support EdDSA algorithm

Removed

  • Breaking: Drop support for Node.js 10
  • No longer accepts PEM encoded keys
  • No longer supports generating unsigned JWTs

Changed

  • Breaking: Reworked exposed API. Please refer to the migration guide for more information.
  • Add support for Node.js 16

3.2.0 — 2021-08-03

Added

  • Add subject_types_supported OpenID Provider Metadata field (by jjbooth74)

3.1.0 — 2020-11-30

Added

3.0.3 — 2020-11-12

Fixed

  • Fix regression: When adding a key to the KeyStore, do not normalize key "use" value to "sig" when already defined

3.0.2 — 2020-10-29

Added

  • Support Nodejs 14.15 LTS

3.0.1 — 2020-10-23

Fixed

  • Include missing files on pack/publish

3.0.0 — 2020-10-22

Added

  • TypeScript type definitions (#48)

Changed

  • Straightened definitions of optional parameters: null is no longer considered as a non valued parameter value; undefined bears that meaning.

2.0.0 — 2020-10-01

Added

Removed

  • No longer support Node 8

1.5.1 — 2020-04-06

Security

1.5.0 — 2020-01-23

Added

  • Add HTTP request object to OAuth2Service's events
  • Add beforeTokenSigning event to OAuth2Service

1.4.0 — 2020-01-15

Security

Fixed

  • Add missing aud claim under Authorization Code Flow

Added

  • Add CORS support

1.3.3 — 2019-09-25

Security

Changed

  • Update license's legal entity.

1.3.2 — 2019-08-09

Security

1.3.1 — 2019-06-07

Security

1.3.0 — 2019-06-03

Added

  • Add revocation endpoint

1.2.0 — 2019-03-19

Added

  • Add Authorization code grant
  • Add Refresh token grant
  • Add Userinfo endpoint

Security

1.1.0 — 2018-08-02

Added

  • Add Resource Owner Password Credentials grant

Fixed

  • Add missing cache control headers on /token responses

1.0.0 — 2018-08-01

Initial release.