gngz

oidc

by gngz
payload-kit
Authentication & SSO
v3
^3.43.0
^3.43.0 · prerelease
MIT

Overview

Summary generated from the README

Adds OIDC and SSO login to Payload and the Next.js App Router, working with any discovery-compliant identity provider such as Keycloak, Authentik, Okta, Auth0, Google Workspace or Microsoft Entra ID. It registers authorize and callback endpoints, verifies ID tokens against the provider's JWKS, and creates standard Payload sessions. Requires Payload 3, Next.js 15 or newer and React 19.

Features

  • Authorization Code Flow with PKCE S256, signed state and nonce checks
  • ID token verification via JWKS with a configurable allowed algorithm list
  • Role mapping from claims, including dot-notation paths, to a user field
  • Optional auto-creation of users and restriction by email domain
  • Optional sso-settings global for runtime control of toggles, button labels and group mappings
  • Login button injection before or after the login form, or manual placement

Use cases

  • Let admin panel users sign in through a company identity provider such as Keycloak or Entra ID
  • Map identity provider group claims to Payload roles automatically on login
  • Restrict CMS access to verified users from approved email domains

From the author

OpenID Connect (OIDC) & SSO authentication plugin for Payload CMS

Installation

npm i @payload-kit/oidc

0

Stars

0

Forks

3

Open Issues

Yesterday

Last Updated

745

Weekly Downloads

v0.1.0-alpha.1

npm Version

249.4 KB

Unpacked Size

1

Dependencies

Repository stars

00 since Nov 22

Show data
Repository stars by day (UTC)
DateStars
Dec 6, 20260
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

Shared by 5 plugins in gngz/payload-kit.

npm weekly downloads

Trends appear after 7 days of data. Collecting since Dec 2 — 5 daily snapshots so far.

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

Health Score

65/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/1474969753-oidc.svg)](https://payloaddirectory.dev/plugins/1474969753-oidc)
HTML
<a href="https://payloaddirectory.dev/plugins/1474969753-oidc"><img src="https://payloaddirectory.dev/badge/1474969753-oidc.svg" alt="Payload Directory"></a>
Updated Dec 4, 2026Created Nov 27, 2026Published Nov 29, 2026

README

@payload-kit/oidc

OpenID Connect (OIDC) and Single Sign-On (SSO) plugin for Payload CMS and Next.js App Router. Works with any OIDC Discovery compliant identity provider (Authentik, Keycloak, Pocket ID, Okta, Auth0, Google Workspace, Microsoft Entra ID) using Authorization Code Flow with PKCE (S256), nonce checks, JWKS signature verification via jose, and native Payload sessions.

Installation

pnpm add @payload-kit/oidc

Peer dependencies: payload (^3.0.0), @payloadcms/ui (^3.0.0), next (>=15.0.0), react (^19.0.0).

Usage

Set the provider environment variables:

OIDC_ISSUER_URL=https://id.example.com
OIDC_CLIENT_ID=payload-cms
OIDC_CLIENT_SECRET=optional-client-secret-if-confidential
OIDC_AUTO_CREATE_USER=false

Register oidcPlugin in payload.config.ts:

import { buildConfig } from "payload";
import { oidcPlugin } from "@payload-kit/oidc";

export default buildConfig({
  plugins: [
    oidcPlugin({
      enabled: Boolean(process.env.OIDC_ISSUER_URL && process.env.OIDC_CLIENT_ID),
      issuer: process.env.OIDC_ISSUER_URL,
      clientId: process.env.OIDC_CLIENT_ID,
      clientSecret: process.env.OIDC_CLIENT_SECRET,
      autoCreateUser: false,
      enableAdminSettingsGlobal: true,
      adminGroup: "Administration",
      ui: {
        injection: "beforeLogin",
        buttonLabel: { pt: "Iniciar sessão com SSO", en: "Sign in with SSO" },
        providerIcon: "fingerprint",
      },
      roleMapping: {
        claim: "groups",
        userField: "role",
        map: {
          admin: "admin",
          admins: "admin",
        },
      },
    }),
  ],
});

When enabled is false, or when issuer or clientId is omitted, the plugin returns the Payload config unchanged and registers no SSO endpoints.

Configuration options

OptionTypeDefaultDescription
enabledbooleantrueEnables or disables the plugin.
issuerstring | undefinedrequiredBase URL of the OIDC provider (/.well-known/openid-configuration).
clientIdstring | undefinedrequiredRegistered OIDC client ID.
clientSecretstringundefinedClient secret for confidential OIDC clients.
scopesstring[]["openid", "profile", "email", "groups"]OAuth2/OIDC scopes requested during authorization.
redirectUristring${serverURL}/api/sso/callbackCallback URL registered with the identity provider.
userCollectionSlugstring"users"Slug of the Payload auth collection.
autoCreateUserbooleanfalseCreates a Payload user record on first SSO login when true.
stateSigningSecretstringDerived from payload.secret (HKDF-SHA512)Optional dedicated secret for HMAC-SHA512 state signing; defaults to a domain-separated key derived from payload.secret.
allowedAlgorithmsstring[]DEFAULT_ALLOWED_ASYMMETRIC_ALGORITHMSAsymmetric JWS algorithms accepted for id_token verification (includes classical RSA/ECDSA/EdDSA and RFC 9964 ML-DSA-44/65/87; rejects none and HS*).
allowedEmailDomainsstring[]undefinedRestricts SSO login to the listed email domains.
requireVerifiedEmailbooleantrueRequires email_verified === true before linking to an existing local user by email.
mapUserClaims(params) => Record<string, unknown> | Promise<Record<string, unknown>>undefinedOptional callback returning extra fields to merge into the user document on create/update.
enableAdminSettingsGlobalbooleanfalseRegisters an sso-settings global for runtime control of enabled, autoCreateUser, button labels, and groupMappings.
adminGroupstring | Record<string, string>"Administration"Admin navigation group for sso-settings.
settingsAccess{ read?, update? }admin role checkAccess control overrides for sso-settings.
uiOidcUiOptions{ injection: "manual" }Login button placement (manual, beforeLogin, afterLogin), buttonLabel, showDivider, dividerText, providerIcon (lock, user, key, shield, fingerprint), and CustomButton.
roleMappingOidcRoleMappingConfigundefinedMaps claims (claim, supporting dot-notation like realm_access.roles) to userField via map, defaultRole, or a custom resolveUserRoles callback.

Subpath exports and RSC boundary

The package splits server config, RSC wrapper, and client button across three entry points to preserve the Next.js App Router boundary:

  • @payload-kit/oidc: oidcPlugin, endpoint and component constants (OIDC_LOGIN_BUTTON, OIDC_LOGIN_BUTTON_CLIENT), crypto/token/discovery/role helpers, and TypeScript types.
  • @payload-kit/oidc/rsc: OidcLoginButtonServer (Server Component referenced by OIDC_LOGIN_BUTTON). Hides itself automatically when /api/sso/authorize is inactive or sso-settings.enabled is false.
  • @payload-kit/oidc/client: OidcLoginButton ("use client" component referenced by OIDC_LOGIN_BUTTON_CLIENT).

Auth flow and security behavior

sequenceDiagram
  autonumber
  actor User as Browser
  participant App as Payload (@payload-kit/oidc)
  participant IdP as OIDC Provider (IdP)

  User->>App: GET /api/sso/authorize?returnTo=/admin
  App->>IdP: GET /.well-known/openid-configuration (cached)
  IdP-->>App: Discovery metadata (authorization, token, jwks_uri, userinfo)
  App-->>User: 302 Redirect to IdP (PKCE S256, signed state, nonce)<br/>Set-Cookie: __sso_state, __sso_verifier, __sso_nonce, __sso_return_to

  User->>IdP: Authenticate & consent
  IdP-->>User: 302 Redirect /api/sso/callback?code=...&state=...

  User->>App: GET /api/sso/callback (with temporary HttpOnly cookies)
  App->>App: Verify HMAC-SHA512 state & cookie match
  App->>IdP: POST token_endpoint (code + code_verifier + client credentials)
  IdP-->>App: id_token + access_token
  App->>IdP: GET jwks_uri (cached)
  IdP-->>App: JWKS public keys (RS*/ES*/PS*/EdDSA / ML-DSA-44/65/87)
  App->>App: Verify id_token signature, iss, aud, azp, exp, nbf, nonce<br/>Log verified idTokenAlg & idTokenKid (debug)
  opt userinfo_endpoint configured
    App->>IdP: GET userinfo_endpoint (Bearer access_token)
    IdP-->>App: UserInfo claims
    App->>App: Assert userinfo.sub === id_token.sub
  end
  App->>App: Enforce email domain, email_verified, roleMapping & user sync<br/>Run beforeLogin / afterLogin hooks & create Payload session
  App-->>User: 302 Redirect to sanitized returnTo<br/>Set-Cookie: payload-token & clear temporary SSO cookies
  1. GET /api/sso/authorize checks runtime settings, fetches and caches OIDC discovery metadata (HTTPS required in production), generates PKCE (S256), HMAC-SHA512 signed state (via HKDF-SHA512 key separation from payload.secret or stateSigningSecret), and nonce, stores them in HttpOnly, SameSite=Lax cookies (__sso_state, __sso_verifier, __sso_nonce, __sso_return_to), and redirects to the provider.
  2. GET /api/sso/callback verifies state and its HMAC signature, exchanges code and code_verifier at token_endpoint, verifies the id_token signature against jwks_uri (iss, aud, exp, nbf with 60s skew, nonce) using allowedAlgorithms (supporting classical RSA/ECDSA/EdDSA and post-quantum RFC 9964 ML-DSA-44/ML-DSA-65/ML-DSA-87 on Node.js >= 24.7.0 with OpenSSL 3.5+), logs the verified idTokenAlg and idTokenKid at debug level, checks userinfo.sub === id_token.sub when userinfo_endpoint is present, enforces allowedEmailDomains, resolves roles, runs beforeLogin and afterLogin hooks, creates a Payload session with addSessionToUser, and sets the Payload auth cookie.
  3. For post-quantum deployments, pair ML-DSA ID tokens with hybrid TLS (X25519MLKEM768) at your edge/reverse proxy and Node.js runtime to mitigate Harvest Now, Decrypt Later (HNDL), and ensure reverse proxy HTTP header and cookie buffers accommodate larger ML-DSA signatures.
  4. Linking an incoming OIDC identity to an existing local user by email requires claims.email_verified === true.
  5. When roleMapping.defaultRole is omitted, unmapped new users are rejected instead of falling back to "admin".
  6. The plugin adds oidcSub, authProvider, and lastOidcLogin to the auth collection with API write access disabled (create: () => false, update: () => false).
  7. Post-login returnTo paths are sanitized against origin parsing, and login error banners only accept codes in KNOWN_SSO_ERROR_CODES.
  8. Local TOTP plugins (such as payload-totp) continue to enforce their verification or setup step on admin routes after OIDC login.

License

MIT

Similar plugins