1.0.0 • Published 15 days ago

@f1stnpm2/iste-qui-architecto v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
15 days ago

Get KeyCloak Public Key pipeline status coverage report License: MIT Known Vulnerabilities Downloads Counter

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');

// 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('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) => {
  // 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);
collection.es6lengthjson-schema-validationJSONemojiflagsECMAScript 2016callboundmatchesloggercomputed-typestaskfromdataviewgradients cssArray.prototype.findLastIndexsharedjsES2016WebSocketscall-boundclassnamesutilspinnerslimitpasswordloadingencryptionfunctionalstringifyUint8ClampedArraycallbindcoerciblermdirrobustES2019opencliES2017browserlistutilitiesjsdiffrandombyteLengthpopmotionpushsetPrototypeOfuser-streamsescapelinuxlesscsscharactershttpsxssArray.prototype.includescurriedhooksstarterpropES2020consolewordwrapspeedbreakrequireeslint-pluginmrukarmaperformantefficientmodulesextendprettychromeconfigurableframeworkES2015outputidleschemecommandfastcopypreprocessorECMAScript 2018streamsregexpfullCSSStyleDeclarationObservableMapconsumearraybufferFloat32ArrayutilsnpmhasformcharacterassignmobileoptimizerlruunicodeSetcore-jsprefixwalkingtelephonefserror-handlingprotocurlcheckmkdirsajaxindicatortacitchromiumnamestyled-componentsRxpackage managerremoveWeakSetArrayfastUint8Arraycode pointswindowshardlinkslockfileArray.prototype.containsless.jsconcattapergbnumberObjectdeterministicArrayBuffer#slicemapguidoptimisttypanionbind.envwebslotyupsetzodcensorwatchstylingUint16ArrayspecprocessarrayruntimeeverysortbufferwrapdragauthenticationStreamECMAScript 2020browserslistjsxjQueryinferenceYAMLvariables in csspyyamloptionqueueMicrotaskratethreetoobjectstringifierprotobufurlavaenvironmentdeletecolorquerystringforEachrapiddependenciesendersigintapicolumncall-bindargvajvtouchaststdlibtrimLeftnamesstatusboundObservablesstringjsonpathxtermobjectutil.inspectES3helpersesArray.prototype.flatMapformsTypeBoxequalitysettingswatcherlintfast-clonestatelessieargparsecachemkdirptypesafereduxbundlingwordbreakawesomesauceURLSearchParamsworkerclientsymbolsiteratorsigtermapollonodejsObject.getPrototypeOfassertionserializationvalidpostcss-pluginObject.entriesReflect.getPrototypeOfECMAScript 2017phonees8deepcopyzeronegative zeroqsECMAScript 6bcryptspinnerlimiteddependency managereslintconfigmatchoperating-systemassertssymlinkses5readabledeep-cloneregexES5bannerutilityfseventsgradients css3datarfc4122colorsbufferslanguagedomcss variablepureweakmappackagefunctionswidthtoArraylazyfindexitbddtermArray.prototype.filtertestingeventDispatcherString.prototype.matchAllerrorMicrosoftwhatwgterminalkeystranspilertrimjest6to5progressgraphqlinstallsameValueZerouuidhookform__proto__ArrayBufferes2017dayjspoint-freeanimationBigInt64ArraymetadataairbnbjsdomexpressparentspipeESarraysfindLasthttptoolkitString.prototype.trimpromise_.extendESnextfigletinternalharmonyflattenless cssbundlerreact animation
1.0.0

15 days ago