npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mock-jwks

v3.3.5

Published

A tool to mock a JWKS for development of microservices who consume jwts signed with RSA

Downloads

413,474

Readme

mock-jwks

A tool to mock a JWKS authentication service for development of microservices CONSUMING authentication and authorization jwts.

Background

If you use jwts for authentication and authorization of your users against your microservices, you want to automatically unit test the authentication in your microservice for security. Happy and unhappy paths. Doing this while actually using a running JWKS deployment (like the auth0 backend) is slow and annoying, so e.g. auth0 suggest you mock their api. This turns out to be somewhat difficult, especially in the case of using RSA for signing of the tokens and not wanting to heavily dependency inject the middleware for authentication in your koa or express app. This is why I made this tool, which requires less changes to your code.

Usage

Consider a basic express app (works also with koa, hapi or graphql):

// api.js
import express from 'express'
import { expressjwt } from 'express-jwt'
import jwksRsa from 'jwks-rsa'
export const createApp = ({ jwksUri }) =>
  express()
    .use(
      // We set up the jwksRsa client as usual (with production host)
      expressjwt({
        secret: jwksRsa.expressJwtSecret({
          cache: false, // We switch off caching to show how things work in ours tests.
          jwksUri,
        }),
        audience: 'private',
        issuer: 'master',
        algorithms: ['RS256'],
      })
    )
    .get('/', (_, res) => res.send('Authenticated'))

You can test this app like so:

// authentication.test.js
// @ts-check
import { createJWKSMock } from 'mock-jwks'
import { createApp } from './api.js'
import supertest from 'supertest'
import { describe, expect, test, onTestFinished } from 'vitest'

// This creates the local PKI
const jwksMock = createJWKSMock('https://levino.eu.auth0.com')
// We start our app.
const app = createApp({
  jwksUri: 'https://levino.eu.auth0.com/.well-known/jwks.json',
})

describe('Some tests for authentication for our api', () => {
  test('should not get access without correct token', async () => {
    // We start intercepting queries (see below)
    onTestFinished(jwksMock.start())
    const { status } = await supertest(app).get('/')
    expect(status).toEqual(401)
  })

  test('should get access with mock token when jwksMock is running', async () => {
    // Again we start intercepting queries
    onTestFinished(jwksMock.start())
    const access_token = jwksMock.token({
      aud: 'private',
      iss: 'master',
    })
    const { status } = await supertest(app)
      .get('/')
      .set('Authorization', `Bearer ${access_token}`)
    expect(status).toEqual(200)
  })
  test('should not get access with mock token when jwksMock is not running', async () => {
    // Now we do not intercept queries. The queries of the middleware for the JKWS will
    // go to the production server and the local key will be invalid.
    const access_token = jwksMock.token({
      aud: 'private',
      iss: 'master',
    })
    const { status } = await supertest(app)
      .get('/')
      .set('Authorization', `Bearer ${access_token}`)
    expect(status).toEqual(500)
  })
})
test('Another example with a non-auth0-style jkwsUri', async () => {
  const jwksMock = createJWKSMock(
    'https://keycloak.somedomain.com',
    '/auth/realm/application/protocol/openid-connect/certs'
  )
  // We start our app.
  const app = createApp({
    jwksUri:
      'https://keycloak.somedomain.com/auth/realm/application/protocol/openid-connect/certs',
  })
  const request = supertest(app)
  onTestFinished(jwksMock.start())
  const access_token = jwksMock.token({
    aud: 'private',
    iss: 'master',
  })
  const { status } = await request
    .get('/')
    .set('Authorization', `Bearer ${access_token}`)
  expect(status).toEqual(200)
})

You can also find this example in the repo.

Custom Mock Server Worker (MSW) usage

Internally this library uses Mock Server Worker (MSW) to create network mocks for the JWKS keyset. Instead of letting mock-jwks run its own msw instance, you can add the required handlers to your running instance.

In this case, instead of calling start()/stop(), provide the mswHandler to to your existing server instance:

// @ts-check
/**
 * @typedef
 */
import createJWKSMock from 'mock-jwks'
import { createApp } from './api.js'
import supertest from 'supertest'
import { beforeAll, beforeEach, describe, expect, test } from 'vitest'
import { setupServer } from 'msw/node'

const jwksMock = createJWKSMock('https://levino.eu.auth0.com')
const app = createApp({
  jwksUri: 'https://levino.eu.auth0.com/.well-known/jwks.json',
})

describe('Some tests for authentication for our api', () => {
  /** @type {import('msw/node').SetupServerApi} */
  let mswServer
  beforeAll(() => {
    mswServer = setupServer()
    mswServer.listen({
      onUnhandledRequest: 'bypass', // We silence the warnings of msw for unhandled requests. Not necessary for things to work.
    })
    return () => mswServer.close()
  })

  beforeEach(() => {
    mswServer.resetHandlers()
  })

  test('Can get access with mock token when handler is attached to msw', async () => {
    // arrange
    mswServer.use(jwksMock.mswHandler)
    const access_token = jwksMock.token({
      aud: 'private',
      iss: 'master',
    })

    // act
    const { status } = await supertest(app)
      .get('/')
      .set('Authorization', `Bearer ${access_token}`)

    // assert
    expect(status).toEqual(200)
  })
  test('Cannot get access with mock token when handler is not attached to msw', async () => {
    // Now we do not intercept queries. The queries of the middleware for the JKWS will
    // go to the production server and the local key will be invalid.
    // arrange
    const access_token = jwksMock.token({
      aud: 'private',
      iss: 'master',
    })

    // act
    const { status } = await supertest(app)
      .get('/')
      .set('Authorization', `Bearer ${access_token}`)

    // assert
    expect(status).toEqual(500)
  })
})

You can also find this example in the repo.

Under the hood

createJWKSMock will create a local PKI and generate a working JWKS.json. Calling jwksMock.start() will use msw to intercept all calls to

;`${jwksBase}${jwksPath ?? '/.well-known/jwks.json'}`

. So when the jwks-rsa middleware gets a token to validate it will fetch the key to verify against from our local PKI instead of the production one and as such, the token is valid when signed with the local private key.

Contributing

You found a bug or want to improve the software? Thank you for your support! Before you open a PR I kindly invite you to read about best practices and subject your contribution to them.