Skip to content

jorgeju4rez/keycloak-public-key

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Get KeyCloak Public Key

Provides access to PEM Public Keys from a KeyCloak server for JWT validation.

This repository is an improvement for the correct functioning of the new versions of keycloak

Original repository

It works correctly in version 21.1.0 of keycloak

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 keycloak-public-key

Usage

const KeyCloakCerts = require('keycloak-public-key');

const keyCloakCerts = new 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.fetch('my-kid')

Example

Verifying the token using koa and jsonwebtoken:

const Koa = require('koa');
const KeyCloakCerts = require('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) => {
  // Check the Authorization header
  if (!(ctx.request.header.autorization && ctx.request.header.authorization.startsWith('Bearer '))) {
    // Authorization header is missing
    ctx.status = 401;
    return;
  }

  // Get the token from the Authorization header, skip 'Bearer ' prefix
  const token = ctx.request.header.authorization.substr(7);

  // decode the token without verification to have the kid value
  const kid = jwt.decode(token, { complete: true }).header.kid;

  // fetch the PEM Public Key
  const publicKey = await keyCloakCerts.fetch(kid);

  if (publicKey) {
    try {
      // Verify and decode the token
      const decoded = jwt.verify(token, publicKey);
      ctx.body = decoded;
    } catch (error) {
      // Token is not valid
      process.stderr.write(error.toString());
      ctx.status = 401;
    }
  } else {
    // KeyCloak has no Public Key for the specified KID
    ctx.status = 401;
  }
});
app.listen(3000);