npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

fastify-keycloak-adapter

v2.3.1

Published

A fastify plugin for Keycloak

Downloads

4,645

Readme

Fastify-Keycloak-Adapter

Node.js CI NPM version

fastify-keycloak-adapter is a keycloak adapter for a Fastify app.

Install

https://www.npmjs.com/package/fastify-keycloak-adapter

npm i fastify-keycloak-adapter
yarn add fastify-keycloak-adapter

Fastify Version

  • Fastify 4 -> npm i fastify-keycloak-adapter
  • Fastify 3 -> npm i [email protected] (deprecated)

Usage

import fastify from 'fastify'
import keycloak, { KeycloakOptions } from 'fastify-keycloak-adapter'

const server = fastify()

const opts: KeycloakOptions = {
  appOrigin: 'http://localhost:8888',
  keycloakSubdomain: 'keycloak.yourcompany.com/auth/realms/realm01',
  clientId: 'client01',
  clientSecret: 'client01secret'
}

server.register(keycloak, opts)

Configuration

  • appOrigin app url, used for redirect to the app when user login successfully (required)

  • keycloakSubdomain keycloak subdomain, endpoint of a realm resource (required)

  • useHttps set true if keycloak server uses https (optional, defaults to false)

  • clientId client id (required)

  • clientSecret client secret (required)

  • scope client scope of keycloak (optional, string[], defaults to ['openid'])

  • callback Relative or absolute URL to receive the response data (optional, defaults to /)

  • retries The number of times to retry before failing. (optional, number, defaults to 3)

  • logoutEndpoint route path of doing logout (optional, defaults to /logout)

  • excludedPatterns string array for non-authorized urls (optional, support ?, * and ** wildcards)

  • autoRefreshToken set true for refreshing token automatically when token has expired (optional, defaults to false)

  • disableCookiePlugin set true if your application register the fastify-cookie plugin itself. Otherwise fastify-cookie will be registered by this plugin, because it's mandatory. (optional, defaults to false)

  • disableSessionPlugin set true if your application register the fastify-session plugin itself. Otherwise fastify-session will be registered by this plugin, because it's mandatory. (optional, defaults to false)

  • userPayloadMapper(userPayload) defined the fields of fastify.session.user (optional)

  • unauthorizedHandler(request, reply) is a function to customize the handling (e.g. the response) of unauthorized requests (optional)

  • bypassFn(request) is a function that returns true if you want to stop the normal authentication workflow and allow the request. It will prevent userPayloadMapper from being called and fastify.session.user from being generated.

  • usePostLogoutRedirect set true to enable compatibility with Keycloak versions 18.0.0 and later, where post_logout_redirect_uri and id_token_hint are used instead of redirect_uri during logout. When set to false, the plugin will default to using the old redirect_uri for backward compatibility. (optional, defaults to false)

Configuration example

import keycloak, { KeycloakOptions, UserInfo } from 'fastify-keycloak-adapter'
import fastify, { FastifyInstance } from 'fastify'

const server: FastifyInstance = fastify()

const opts: KeycloakOptions = {
  appOrigin: 'http://localhost:8888',
  keycloakSubdomain: 'keycloak.mycompany.com/auth/realms/myrealm',
  useHttps: false,
  usePostLogoutRedirect: false,
  clientId: 'myclient01',
  clientSecret: 'myClientSecret',
  logoutEndpoint: '/logout',
  excludedPatterns: ['/metrics', '/manifest.json', '/api/todos/**'],
  callback: '/hello'
}

server.register(keycloak, opts)

Set userPayloadMapper

defined the fields of fastify.session.user, use the payload from JWT token

use DefaultToken in default case

or you should define the type by yourself, in case the keycloak server has custom payload

import { KeycloakOptions, DefaultToken } from 'fastify-keycloak-adapter'

const userPayloadMapper = (tokenPayload: unknown) => ({
  account: (tokenPayload as DefaultToken).preferred_username,
  name: (tokenPayload as DefaultToken).name
})

const opts: KeycloakOptions = {
  // ...
  userPayloadMapper: userPayloadMapper
}

Set unauthorizedHandler

Provides a custom handler for unauthorized requests.

import { FastifyReply, FastifyRequest } from 'fastify'
import { KeycloakOptions } from 'fastify-keycloak-adapter'

const unauthorizedHandler = (request: FastifyRequest, reply: FastifyReply) => {
  reply.status(401).send(`Invalid request`)
}

const opts: KeycloakOptions = {
  // ...
  unauthorizedHandler: unauthorizedHandler
}

Set bypassFn

Provides a function that returns true if you want to stop the normal authentication workflow and allow the request.

import { FastifyReply, FastifyRequest } from 'fastify'
import { KeycloakOptions } from 'fastify-keycloak-adapter'

const bypassFn = (request: FastifyRequest) => {
  return Math.random() * 6 < 1 // russian roulette of security DO NOT USE IT !
}

const opts: KeycloakOptions = {
  // ...
  bypassFn: bypassFn
}

Disable mandatory plugin registration

Use the options to disable the cookie and session plugin registration, in case you want to initialize the plugins yourself, to provide your own set of configurations for these plugins.

import fastify from 'fastify'
import fastifyCookie from '@fastify/cookie'
import session from '@fastify/session'
import keycloak, { KeycloakOptions } from 'fastify-keycloak-adapter'

const server = fastify()

server.register(fastifyCookie)
server.register(session, {
  secret: '<SOME_SECRET>',
  cookie: {
    secure: false
  }
})

const opts: KeycloakOptions = {
  // ...
  disableCookiePlugin: true,
  disableSessionPlugin: true
}
server.register(keycloak, opts)

Get login user

use request.session.user

server.get('/users/me', async (request, reply) => {
  const user = request.session.user
  return reply.status(200).send({ user })
})

Get OpenID Connect (OIDC) tokens

in some case, you may want to handle the id_token (or access_token, refresh_token) by yourself

use request,session.grant can get the GrantResponse object

const id_token = request.session.grant.response?.id_token
console.log('id_token', id_token)
const access_token = request.session.grant.response?.access_token
console.log('access_token', access_token)
const refresh_token = request.session.grant.response?.refresh_token
console.log('refresh_token', refresh_token)

License

MIT License