alexdeia

payload keycloak

by alexdeia
Authentication & SSO
v3
^3.84.1
MIT

Overview

Summary generated from the README

Replaces local Payload users and passwords with Keycloak sign-in. It registers an auth strategy that verifies Keycloak access tokens via JWKS, creates users on first login, and adds admin login and logout through Authorization Code with PKCE. Permissions are read from a userinfo claim and exposed through access helpers. Requires a public Keycloak client with Revoke Refresh Token turned off, and Payload 3.

Features

  • OIDC auth strategy verifying Keycloak tokens from Bearer header or httpOnly session cookie
  • Admin login and logout via Authorization Code with PKCE and Keycloak end-session handoff
  • Silent refresh of expired access tokens using the refresh-token cookie
  • Permission checks from nested boolean userinfo claims with can, withKeycloakAccess and withAuth helpers
  • Users created on first login by Keycloak sub, with keycloakSub, email and name fields added
  • Per-token userinfo caching with configurable TTL and request timeouts

Use cases

  • Secure the Payload admin panel with an existing Keycloak realm instead of local passwords
  • Map Keycloak permission claims to collection and global access control in Payload
  • Protect custom API endpoints with Keycloak-verified bearer tokens

From the author

Keycloak SSO authentication for Payload CMS 3: OIDC auth strategy, admin login/logout, silent refresh and permission-based access control

Installation

npm i payload-keycloak

0

Stars

0

Forks

9

Open Issues

3 days ago

Last Updated

12

Weekly Downloads

v1.0.1

npm Version

117.5 KB

Unpacked Size

1

Dependencies

GitHub stars

00 since Sep 13

Show data
GitHub stars by day (UTC)
DateStars
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
Nov 21, 20260
Nov 20, 20260
Nov 19, 20260
Nov 18, 20260
Nov 17, 20260
Nov 16, 20260
Nov 15, 20260
Nov 14, 20260
Nov 13, 20260
Nov 12, 20260
Nov 11, 20260
Nov 10, 20260
Nov 9, 20260
Nov 8, 20260
Nov 7, 20260
Nov 6, 20260
Nov 5, 20260
Nov 4, 20260
Nov 3, 20260
Nov 2, 20260
Nov 1, 20260
Oct 31, 20260
Oct 30, 20260
Oct 29, 20260
Oct 28, 20260
Oct 27, 20260
Oct 26, 20260
Oct 25, 20260
Oct 24, 20260
Oct 23, 20260
Oct 22, 20260
Oct 21, 20260
Oct 20, 20260
Oct 19, 20260
Oct 18, 20260
Oct 17, 20260
Oct 16, 20260
Oct 15, 20260
Oct 14, 20260
Oct 13, 20260
Oct 12, 20260
Oct 11, 20260
Oct 10, 20260
Oct 9, 20260
Oct 8, 20260
Oct 7, 20260
Oct 6, 20260
Oct 5, 20260
Oct 4, 20260
Oct 3, 20260
Oct 2, 20260
Oct 1, 20260
Sep 30, 20260
Sep 29, 20260
Sep 28, 20260
Sep 27, 20260
Sep 26, 20260
Sep 25, 20260
Sep 24, 20260
Sep 23, 20260
Sep 22, 20260
Sep 21, 20260
Sep 20, 20260
Sep 19, 20260
Sep 18, 20260
Sep 17, 20260
Sep 16, 20260
Sep 15, 20260
Sep 14, 20260
Sep 13, 20260
npm weekly downloads

7−253 since Sep 19

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 5, 20267
Dec 4, 20266
Dec 3, 20266
Dec 2, 20267
Dec 1, 20267
Nov 30, 20268
Nov 29, 202612
Nov 28, 202613
Nov 27, 202612
Nov 26, 202613
Nov 25, 202612
Nov 24, 202610
Nov 23, 202611
Nov 22, 202610
Nov 21, 202612
Nov 20, 202612
Nov 19, 202615
Nov 18, 202619
Nov 17, 202621
Nov 16, 202621
Nov 15, 202621
Nov 14, 202618
Nov 13, 202619
Nov 12, 202618
Nov 11, 202613
Nov 10, 202614
Nov 9, 202616
Nov 8, 202614
Nov 7, 202625
Nov 6, 202628
Nov 5, 202626
Nov 4, 202626
Nov 3, 202623
Nov 2, 202624
Nov 1, 202624
Oct 31, 202618
Oct 30, 202622
Oct 29, 202621
Oct 28, 202621
Oct 27, 202624
Oct 26, 202622
Oct 25, 202623
Oct 24, 202623
Oct 23, 202614
Oct 22, 202619
Oct 21, 202619
Oct 20, 202617
Oct 19, 202614
Oct 18, 202614
Oct 17, 202614
Oct 16, 202616
Oct 15, 202615
Oct 14, 202615
Oct 13, 202616
Oct 12, 202617
Oct 11, 202617
Oct 10, 202614
Oct 9, 202613
Oct 8, 202610
Oct 7, 202613
Oct 6, 202613
Oct 5, 202614
Oct 4, 202614
Oct 3, 202613
Oct 2, 202616
Oct 1, 202619
Sep 30, 202630
Sep 29, 202632
Sep 28, 202639
Sep 27, 202651
Sep 26, 202684
Sep 25, 2026340
Sep 24, 2026336
Sep 23, 2026322
Sep 22, 2026318
Sep 21, 2026309
Sep 20, 2026294
Sep 19, 2026260

Each point is npm's rolling 7-day download count.

Health Score

55/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1372973491-root.svg)](https://payloaddirectory.dev/plugins/1372973491-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1372973491-root"><img src="https://payloaddirectory.dev/badge/1372973491-root.svg" alt="Payload Directory"></a>
Updated Dec 2, 2026Created Sep 16, 2026Published Sep 16, 2026

README

payload-keycloak

SSO-only authentication for Payload CMS 3 against Keycloak. No local users, no passwords, no extra auth framework — one dependency (jose) on top of the standard OIDC endpoints.

[!IMPORTANT] 🤖 This package is largely AI-generated.

What it does

  • Auth strategy keycloak — verifies a Keycloak access token (JWKS + issuer) taken from Authorization: Bearer … or from the httpOnly session cookie, fetches /userinfo (cached per token) and attaches its permissions claim to req.user. Users are created on first sight by sub; keycloakSub, email and name are added to your auth collection unless it already declares them. A lost first-login create race is retried as a lookup, so parallel first requests do not turn into a silent 403.
  • Admin login via Authorization Code + PKCE (S256) for a public client: GET /api/auth/login → Keycloak → GET /api/auth/callback → cookies → back to /admin. The /admin/login view redirects straight to Keycloak through a beforeLogin component.
  • Silent refresh — an expired access token in the cookie is refreshed with the refresh-token cookie. /api/users/me reports the refresh token's exp, so Payload's inactivity timers follow the Keycloak SSO session; POST /api/users/refresh-token and /api/users/logout are wired up too. Bearer requests are never refreshed — the caller owns its own token.
  • Logout — the logout button goes to GET /api/auth/logout, which clears the cookies and hands off to the Keycloak end-session endpoint with id_token_hint.
  • Access helpers — authenticated, can('posts.edit'), withKeycloakAccess, withKeycloakGlobalAccess, withAuth, plus permissionsOf(user) for ad-hoc checks.

Install

pnpm add payload-keycloak

Usage

import { buildConfig } from 'payload'
import {
  authenticated,
  can,
  keycloakAuth,
  withAuth,
  withKeycloakAccess,
} from 'payload-keycloak'

const rules = { read: authenticated, write: can('posts.edit') }

export default buildConfig({
  admin: { user: 'users' },
  collections: withKeycloakAccess([Users, Posts], rules, ['users']),
  endpoints: [{ path: '/report', method: 'get', handler: withAuth(reportHandler) }],
  plugins: [
    keycloakAuth({
      url: process.env.KEYCLOAK_URL,           // https://sso.example.com
      realm: process.env.KEYCLOAK_REALM,
      clientId: process.env.KEYCLOAK_CLIENT_ID, // public client, PKCE S256
      serverURL: process.env.SERVER_URL,        // https://app.example.com
      basePath: process.env.BASE_PATH,          // '' | '/sub-path'
    }),
  ],
})

The auth collection keeps its own access; the plugin only sets auth.disableLocalStrategy, adds the fields, the strategy and the me / refresh / afterLogout hooks.

Run payload generate:importmap after adding the plugin — the admin login and logout components are resolved through your app's import map.

Keycloak client

Public client, Standard flow, PKCE S256, with:

  • redirect URI {serverURL}{basePath}/api/auth/callback
  • post-logout redirect URI {serverURL}{basePath}/admin

Revoke Refresh Token must be OFF — see Limits.

Permissions

Permissions are read from a userinfo claim as nested booleans:

{ "permissions": { "posts": { "edit": true } } }

can('posts.edit') passes when that path is exactly true. Point permissionsClaim at whatever claim your realm populates; a user whose userinfo cannot be reached stays authenticated with empty permissions.

Options

OptionDefault
url, realm, clientId, serverURLrequiredmissing one throws at config build
basePath''Next.js basePath
usersSlug'users'auth collection
scope'openid'
allowedOrigins—extra origins allowed to send the session cookie; serverURL is always allowed
permissionsClaim'permissions'userinfo claim holding nested boolean permissions
userInfoTtl300seconds
internalHosts—Host values of trusted in-network callers that read without a token as a shared user with no permissions; requires the ingress to route by its public host only
messagesEnglishadmin UI texts
getKeyremote JWKSJWTVerifyGetKey override for tests
enabledtrue

Cookie names follow Payload's cookiePrefix: {prefix}-token (access, the cookie Payload itself owns), {prefix}-refresh, {prefix}-id-token, and {prefix}-oidc-login during the login redirect. Their domain / sameSite / secure attributes come from the auth collection's auth.cookies, so the cookies this plugin writes and the ones Payload rewrites carry identical scope. secure defaults to whether serverURL is https.

The plugin also forces auth.removeTokenFromResponses: the access token is a Keycloak credential for the whole realm, so it stays in the httpOnly cookie and never reaches the me or refresh-token JSON body.

Timeouts and caching

  • /userinfo runs on every authenticated request and is aborted after 5 s; the token endpoint (login, refresh) after 10 s.
  • A successful /userinfo is cached per token for userInfoTtl, capped by the token's own exp.
  • A failed /userinfo is cached for 15 s, but only a transport failure or a 5xx. A 401 is never cached, so a revoked session loses its permissions on the very next request. It does not lose the session itself: verification is offline (JWKS, no introspection), so the access token keeps verifying until its own exp and the 401 is swallowed exactly like an outage — still authenticated, no permissions. Reads survive until the token expires and the refresh then fails.
  • Repeated refreshes with the same refresh token share one in-flight request for 60 s, which keeps refresh-token rotation from invalidating a token two parallel requests are both spending.

Limits (by design)

  • aud is not validated; gate access with permissions instead.
  • The userinfo cache (positive and negative) and refresh coalescing live in process memory — fine for one replica.
  • Keycloak's Revoke Refresh Token must be OFF. Admin pages are server-rendered without canSetHeaders, so a refresh that happens there cannot write the rotated cookies back and the browser keeps re-sending the original refresh token; with rotation on, once the 60 s coalescing window lapses the next render replays a spent token and bounces the user through Keycloak and back — a flicker with lost form state, not a clean auth error. The coalescing window is per-process, which is the other thing rotation would break at more than one replica.
  • Errors from the token endpoint surface with Keycloak's own HTTP status (400 on an expired or revoked refresh token). Payload returns the error message to the client for any status other than 500, so message carries the status only; Keycloak's response body is attached to KeycloakError.body instead, which stays server-side and reaches the log.
  • A transport-level failure or timeout against the token endpoint carries no status and surfaces as a plain 500.
  • Every *Url serverProp the plugin passes to an admin component is app-relative, without basePath — the component prepends it. redirect() from next/navigation prepends basePath on its own, so only components rendering a plain anchor add it explicitly. Prepending it in both places gives a doubled prefix that is invisible when basePath is empty; dev/plugin.int.spec.ts pins the rule against a non-empty one.

Development

The dev/ folder is a Payload app that loads the plugin from src/.

cp dev/.env.example dev/.env
pnpm install
pnpm dev            # http://localhost:3000/admin
pnpm test:int       # vitest, against an in-memory MongoDB and a fake IdP
pnpm test:e2e       # playwright

pnpm generate:importmap regenerates dev/app/(payload)/admin/importMap.js after a component is added or renamed.

License

MIT

Similar plugins