Back to Jose

Function: createRemoteJWKSet()

docs/jwks/remote/functions/createRemoteJWKSet.md

6.2.122.7 KB
Original Source

Function: createRemoteJWKSet()

šŸ’— Help the project

Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by becoming a sponsor.

ā–ø createRemoteJWKSet(url, options?): RemoteJWKSet

Creates a resolver for a JSON Web Key Set available at an HTTP(S) URL. Fetches the JSON Web Key Set when the cache is missing or stale. An unmatched key triggers another fetch only when cooldownDuration has elapsed since the last successful fetch. Selection uses the header's "alg" and "kid" and respects the JWK's "use" and "key_ops". Exactly one key must match.

If multiple keys match, the thrown util/errors.JWKSMultipleMatchingKeys error exposes an async iterator over the matching keys. The example below shows how to attempt verification with each.

[!NOTE]
Only public signature verification keys are supported, not public encryption keys.

This function is exported (as a named export) from the main 'jose' module entry point as well as from its subpath export 'jose/jwks/remote'.

Parameters

ParameterTypeDescription
urlURLURL to fetch the JSON Web Key Set from.
options?RemoteJWKSetOptionsOptions for the remote JSON Web Key Set.

Returns

RemoteJWKSet

Examples

js
const JWKS = jose.createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'))

const { payload, protectedHeader } = await jose.jwtVerify(jwt, JWKS, {
  issuer: 'urn:example:issuer',
  audience: 'urn:example:audience',
})
console.log(protectedHeader)
console.log(payload)

Opting-in to multiple JWKS matches using createRemoteJWKSet

js
const options = {
  issuer: 'urn:example:issuer',
  audience: 'urn:example:audience',
}
const { payload, protectedHeader } = await jose
  .jwtVerify(jwt, JWKS, options)
  .catch(async (error) => {
    if (error instanceof jose.errors.JWKSMultipleMatchingKeys) {
      for await (const publicKey of error) {
        try {
          return await jose.jwtVerify(jwt, publicKey, options)
        } catch (innerError) {
          if (innerError instanceof jose.errors.JWSSignatureVerificationFailed) {
            continue
          }
          throw innerError
        }
      }
      throw new jose.errors.JWSSignatureVerificationFailed()
    }

    throw error
  })
console.log(protectedHeader)
console.log(payload)