Get KeyCloak Public Key
Provides access to PEM Public Keys from a KeyCloak server for JWT validation.
Introduction
KeyCloak has a bunch of libraries, but for NodeJs the only solution is a Connect based adapter. In case you want to use koa, or something else, you are toast with your token.
This module provides access to the PEM encoded Public Key used for the token based on the KID value, so you can validate the token with anything you want.
The module has no dependencies, the algorithm used to reconstruct the PEM encoded value from the modulus and the exponent is taken from tracker1's solution.
Features
The idea is to keep this simple and stupid, so nothing fancy is included. It can download the certificates JSON from a KeyCloak server, find the one with matching KID value, and reconstruct the Public Key in PEM format. End of story.
If you need improved behavior like caching of Public Keys, you can easily implement one.
Support custom agent for request, and caching requests. For enable cache need add cacheExpire param
Installation
$ npm install --save get-keycloak-public-key
Usage
const KeyCloakCerts = ; const keyCloakCerts = 'https://my-keycloak.com' 'my-realm'; // You can also pass the full URL instead, as a single argument:// 'https://my-keycloak.com/auth/realms/my-realm/protocol/openid-connect/certs' const publicKey = keyCloakCerts;
If your need using proxy on fetch requests or keep alive agent, you need add param agent If your want cache request to keycloak, you need add expire param, defaults cache is disabled
const https = ;const KeyCloakCerts = ;const expireMs = 86400000; // one dayconst keyCloakCerts = 'https://my-keycloak.com' 'my-realm' keepAlive: true expireMs; // You can also pass the full URL instead, as a single argument:// 'https://my-keycloak.com/auth/realms/my-realm/protocol/openid-connect/certs' const publicKey = keyCloakCerts;
Example
Verifying the token using koa and jsonwebtoken:
const Koa = ;const KeyCloakCerts = ;const jwt = ; const keyCloakCerts = 'https://my-keycloak.com' 'my-realm';const app = ;app;app;