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 🙏

© 2024 – Pkg Stats / Ryan Hefner

get-jwks

v9.0.2

Published

Fetch utils for JWKS keys

Downloads

236,446

Readme

get-jwks

ci

Fetch utils for JWKS keys

Installation

npm install get-jwks

Usage

Options

const https = require('node:https')
const buildGetJwks = require('get-jwks')

const getJwks = buildGetJwks({
  max: 100,
  ttl: 60 * 1000,
  timeout: 5000,
  issuersWhitelist: ['https://example.com'],
  checkIssuer: (issuer) => {
    return issuer === 'https://example.com'
  },
  providerDiscovery: false,
  agent: new https.Agent({
    keepAlive: true,
  }),
})
  • max: Max items to hold in cache. Defaults to 100.
  • ttl: Milliseconds an item will remain in cache. Defaults to 60s.
  • timeout: Specifies how long it should wait to retrieve a JWK before it fails. The time is set in milliseconds. Defaults to 5s.
  • issuersWhitelist: Array of allowed issuers. By default all issuers are allowed.
  • allowedDomains: This has been deprecated and replaced with issuersWhitelist.
  • checkIssuer: Optional user defined function to validate a token's domain.
  • providerDiscovery: Indicates if the Provider Configuration Information is used to automatically get the jwks_uri from the OpenID Provider Discovery Endpoint. This endpoint is exposing the Provider Metadata. With this flag set to true the domain will be treated as the OpenID Issuer which is the iss property in the token. Defaults to false. Ignored if jwksPath is specified.
  • jwksPath: Specify a relative path to the jwks_uri. Example /otherdir/jwks.json. Takes precedence over providerDiscovery. Optional.
  • agent: The custom agent to use for requests, as specified in node-fetch documentation. Defaults to null.

max and ttl are provided to lru-cache.

getJwk

const buildGetJwks = require('get-jwks')

const getJwks = buildGetJwks()

const jwk = await getJwks.getJwk({
  domain: 'https://example.com/',
  alg: 'token_alg',
  kid: 'token_kid',
})

Calling the asynchronous function getJwk will fetch the JSON Web Key, and verify if any of the public keys matches the provided alg (if any) and kid values. It will cache the matching key so if called again it will not make another request to retrieve a JWKS. It will also use a cache to store stale values which is used in case of errors as a fallback mechanism.

  • domain: A string containing the domain (e.g. https://www.example.com/, with or without trailing slash) from which the library should fetch the JWKS. If providerDiscovery flag is set to false get-jwks will add the JWKS location (.well-known/jwks.json) to form the final url (ie: https://www.example.com/.well-known/jwks.json) otherwise the domain will be treated as tthe openid issuer and the retrival will be done via the Provider Discovery Endpoint.
  • alg: The alg header parameter is an optional parameter that represents the cryptographic algorithm used to secure the token. You will find it in your decoded JWT.
  • kid: The kid is a hint that indicates which key was used to secure the JSON web signature of the token. You will find it in your decoded JWT.

getPublicKey

const buildGetJwks = require('get-jwks')

const getJwks = buildGetJwks()

const publicKey = await getJwks.getPublicKey({
  domain: 'https://exampe.com/',
  alg: 'token_alg',
  kid: 'token_kid',
})

Calling the asynchronous function getPublicKey will run the getJwk function to retrieve a matching key, then convert it to a PEM public key. It requires the same arguments as getJwk.

Integration Examples

This library can be easily used with other JWT libraries.

@fastify/jwt

@fastify/jwt is a Json Web Token plugin for Fastify.

The following example includes a scenario where you'd like to varify a JWT against a valid JWK on any request to your Fastify server. Any request with a valid JWT auth token in the header will return a successful response, otherwise will respond with an authentication error.

const Fastify = require('fastify')
const fjwt = require('@fastify/jwt')
const buildGetJwks = require('get-jwks')

const fastify = Fastify()
const getJwks = buildGetJwks()

fastify.register(fjwt, {
  decode: { complete: true },
  secret: (request, token, callback) => {
    const {
      header: { kid, alg },
      payload: { iss },
    } = token
    getJwks
      .getPublicKey({ kid, domain: iss, alg })
      .then(publicKey => callback(null, publicKey), callback)
  },
})

fastify.addHook('onRequest', async (request, reply) => {
  await request.jwtVerify()
})

fastify.listen(3000)

fast-jwt

fast-jwt is a fast JSON Web Token implementation.

The following example shows how to use JWKS in fast-jwt via get-jwks.

const { createVerifier } = require('fast-jwt')
const buildGetJwks = require('get-jwks')

// well known url of the token issuer
// often encoded as the `iss` property of the token payload
const domain = 'https://...'

const getJwks = buildGetJwks({ issuersWhitelist: [...]})

// create a verifier function with key as a function
const verifyWithPromise = createVerifier({
  key: async function ({ header }) {
    const publicKey = await getJwks.getPublicKey({
      kid: header.kid,
      alg: header.alg,
      domain,
    })
    return publicKey
  },
})

const payload = await verifyWithPromise(token)