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.
Installation
$ npm install --save get-keycloak-public-key
Usage
const KeyCloakCerts = require('get-keycloak-public-key');
const keyCloakCerts = new KeyCloakCerts('https://my-keycloak.com', 'my-realm');
const publicKey = keyCloakCerts.fetch('my-kid')
Example
Verifying the token using koa and jsonwebtoken:
const Koa = require('koa');
const KeyCloakCerts = require('get-keycloak-public-key');
const jwt = require('jsonwebtoken');
const keyCloakCerts = new KeyCloakCerts('https://my-keycloak.com', 'my-realm');
const app = new Koa();
app.use(async (ctx) => {
if (!(ctx.request.header.autorization && ctx.request.header.authorization.startsWith('Bearer '))) {
ctx.status = 401;
return;
}
const token = ctx.request.header.authorization.substr(7);
const kid = jwt.decode(token, { complete: true }).header.kid;
const publicKey = await keyCloakCerts.fetch(kid);
if (publicKey) {
try {
const decoded = jwt.verify(token, publicKey);
ctx.body = decoded;
} catch (error) {
process.stderr.write(error.toString());
ctx.status = 401;
}
} else {
ctx.status = 401;
}
});
app.listen(3000);