Dev › Gnuboard

Adding OIDC SSO login with PKCE and Keycloak to Gnuboard5

Design OIDC SSO in Gnuboard5 v5.6.58 with PKCE S256, JWKS ID token checks, AES-256-GCM AAD secrets, and RP-Initiated Logout verified on Keycloak 26.8.2.

Adding OIDC SSO login with PKCE and Keycloak to Gnuboard5

Adding OIDC SSO to an existing Gnuboard5 (v5.6.58) installation without breaking member roles or sessions requires explicit iss+sub account linking, PKCE and JWKS verification, and encrypted admin settings instead of email auto-matching. Here is how commit 64c083440 implements those pieces, verified locally with PHP 8.5.13, MariaDB 11.8, Keycloak 26.8.2, and tests/oidc.php.

Every code excerpt and test result in this post comes from Gnuboard5 v5.6.58 (public commit 64c083440), firebase/php-jwt v7.2.2, and Docker Compose (php:8.5-apache-trixie, mariadb:11.8, quay.io/keycloak/keycloak:26.8.2).

Why wiring OIDC SSO into Gnuboard5 breaks simple email matching

In running Gnuboard5 locally with Docker Compose and Dev Containers and storing board attachments in S3 with presigned URLs, the container and storage layers stayed decoupled from core member tables. Authentication is different: an internal portal or legacy Gnuboard5 site already owns g5_member roles, board permissions, and admin privileges.

Quick OIDC tutorials often query g5_member by the email claim and call set_session('ss_mb_id', ...) directly. That shortcut creates three real production risks. First, emails can change or go unverified on the IdP, opening an account-takeover path to admin accounts. Second, bypassing bbs/login_check.php drops session ID regeneration (session_regenerate_id(true)), blocked/withdrawn member checks, email-verification gates, and YoungCart cart restoration. Third, unlinking an SSO account or disabling OIDC leaves existing SSO sessions active.

ApproachIdentity keySession & permission consistencyMain trade-off
Email auto-matching + raw session writeemail claimLow (skips shared login checks)Account takeover if email changes or is unverified
Just-in-time (JIT) auto-registrationiss + subCreates separate new accountsCannot inherit existing member or admin roles
Explicit account linking + shared session helperiss + sub (bound after password check)High (reuses g5_start_member_login_session)Requires a one-time link step per existing member

This design is not the right fit if you need automatic first-login account provisioning (JIT) for brand-new users or multiple simultaneous OIDC providers. It targets existing Gnuboard5 sites that must preserve current member levels and board permissions while federating login through a single OIDC IdP.

Single-migration schema and hook-based integration

Commit 64c083440 packages all schema changes into a single idempotent migration (migrations/20261203_002_oidc_settings.sql), matching install/gnuboard5.sql for fresh installs and adm/dbupgrade.php for upgrades. It adds cf_oidc_settings text NULL to g5_config and creates g5_oidc_identity:

1
2
3
4
5
6
7
8
9
10
11
CREATE TABLE `g5_oidc_identity` (
  `identity_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `issuer` varbinary(255) NOT NULL,
  `subject` varbinary(255) NOT NULL,
  `mb_no` int(11) NOT NULL,
  `linked_at` datetime NOT NULL,
  PRIMARY KEY (`identity_id`),
  UNIQUE KEY `issuer_subject` (`issuer`,`subject`),
  UNIQUE KEY `issuer_member` (`issuer`,`mb_no`),
  KEY `member` (`mb_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_uca1400_ai_ci

Using varbinary(255) instead of varchar matters because OIDC sub values are case-sensitive opaque strings. Binary columns enforce exact byte matching regardless of MariaDB’s case-insensitive collation, and the two unique indexes (issuer_subject and issuer_member) enforce a strict 1:1 mapping per issuer at the database layer.

Core integration lives in extend/oidc.extend.php, which registers UI and logout hooks only on PHP 8.0+ when OIDC is enabled:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// extend/oidc.extend.php
if (PHP_VERSION_ID >= 80000) {
    require_once G5_PLUGIN_PATH . '/oidc/oidc.lib.php';

    if (g5_oidc_enabled()) {
        add_replace('social_login_buttons', 'g5_oidc_add_login_button', G5_HOOK_DEFAULT_PRIORITY, 2);
        add_event('member_login_tail', 'g5_oidc_render_login_button', G5_HOOK_DEFAULT_PRIORITY, 1);
        add_event('outlogin_provider_buttons', 'g5_oidc_render_login_button', G5_HOOK_DEFAULT_PRIORITY, 1);
        add_event('register_form_after', 'g5_oidc_account_button', G5_HOOK_DEFAULT_PRIORITY, 1);
        add_replace('member_logout_provider_url', 'g5_oidc_logout_url', G5_HOOK_DEFAULT_PRIORITY, 2);
    }

    if (get_session('ss_g5_oidc_session')) {
        add_event('common_header', 'g5_oidc_check_login_session');
    }

    add_event('member_leave', 'g5_oidc_member_leave', G5_HOOK_DEFAULT_PRIORITY, 1);
    add_event('member_delete_after', 'g5_oidc_member_delete', G5_HOOK_DEFAULT_PRIORITY, 1);
}

When OIDC is disabled, /bbs/login.php renders zero SSO buttons. After saving an active configuration in the admin panel, a single SSO button appears below the standard login form. The member_leave and member_delete_after hooks stay registered unconditionally so deleting or withdrawing a member always cleans up g5_oidc_identity rows (verified via source inspection in extend/oidc.extend.php rather than running a live member deletion).

Gnuboard5 login page showing the OIDC SSO button below the standard login form Figure 1. /bbs/login.php in the isolated local Docker Compose environment (127.0.0.1:18080) after enabling OIDC, rendering the default key icon (fa-key) and the Korean label 사내 통합인증 로그인 (“Internal SSO Login”).

Authorization Code with PKCE, ID token checks, and redirect hardening

The login flow uses standard Authorization Code with PKCE (S256) and verifies every browser parameter and backchannel payload explicitly:

sequenceDiagram
    participant Browser
    participant PHP as Gnuboard5 (plugin/oidc)
    participant IdP as OIDC IdP (Keycloak)
    Browser->>PHP: GET /plugin/oidc/login.php
    PHP->>IdP: Fetch Discovery (backchannel)
    PHP-->>Browser: 302 auth (state, nonce, S256)
    Browser->>IdP: User authenticates
    IdP-->>Browser: 302 callback.php (code, state, iss)
    Browser->>PHP: GET /plugin/oidc/callback.php
    PHP->>IdP: Token exchange + JWKS (backchannel)
    PHP->>PHP: Verify RS256, 7 claims, and sub link
    PHP-->>Browser: 302 return_url (regenerate session)

g5_oidc_start() generates 256-bit state, nonce, and PKCE verifier values with random_bytes(32) and stores them in ss_g5_oidc_flow with a 600-second TTL. plugin/oidc/callback.php validates state with hash_equals() and unsets the flow immediately for one-time use. Before redirecting, G5OidcProvider::discover() checks that the metadata issuer matches the saved value and confirms support for RS256, PKCE S256, and client_secret_basic. When discovery advertises authorization_response_iss_parameter_supported: true, the callback enforces RFC 9207 iss matching to block issuer mix-up attacks.

For ID token verification, plugin/oidc/provider.php uses firebase/php-jwt v7.2.2, but filters JWKS entries first so only RSA / RS256 / use=sig / key_ops=verify keys reach JWK::parseKeySet(). After signature validation, it checks seven strict claim rules:

1
2
3
4
5
6
7
8
9
10
11
// plugin/oidc/provider.php (excerpt)
$claims = JWT::decode($idToken, JWK::parseKeySet(array('keys' => $keys), 'RS256'));

if (($claims->iss ?? null) !== $this->issuer || (array) ($claims->aud ?? array()) !== array($this->clientId)
    || (property_exists($claims, 'azp') && $claims->azp !== $this->clientId)
    || !is_int($claims->exp ?? null) || !is_int($claims->iat ?? null)
    || $claims->iat > time() || $claims->iat >= $claims->exp || $claims->exp <= time()
    || !is_string($claims->nonce ?? null) || !hash_equals($nonce, $claims->nonce)
    || !is_string($claims->sub ?? null) || !preg_match('/\A[\x21-\x7e]{1,255}\z/', $claims->sub)) {
    throw new RuntimeException('Invalid OpenID Connect ID token claims');
}

Post-login return URLs pass through g5_oidc_return_url(), which decodes HTML entities and loops rawurldecode() up to four times. Any control character, backslash, protocol-relative path (//), embedded user:pass@, or origin mismatch (scheme, host, or port) falls back to G5_URL, blocking double-encoded open redirects such as %252f%252fother.example.test.

Explicit account linking, shared login sessions, and RP-Initiated Logout

An unlinked IdP account never triggers auto-registration; the callback rejects it with HTTP 403. To bind an account, an already signed-in member opens /plugin/oidc/account.php and re-enters their local password with a valid CSRF token. A wrong password returns HTTP 403. A valid password starts a PKCE flow with prompt=login so the user must authenticate freshly at the IdP before g5_oidc_identity records the link. Attempting to bind an IdP subject already owned by another member fails with HTTP 409.

On a successful SSO login, the callback calls g5_start_member_login_session($mb, true)—the same helper shared with bbs/login_check.php—to regenerate the session ID and restore YoungCart carts via shop_restore_login_cart() when enabled (verified by source inspection, as the local test stack ran standard Gnuboard5 without YoungCart). It also writes ss_g5_oidc_session (member_no, issuer, client_id, identity_id, logout_endpoint).

On every subsequent request, g5_oidc_check_login_session() runs on the common_header hook. It re-checks that OIDC is still enabled, issuer and client_id still match, g5_oidc_member_allowed() passes, and the exact identity_id still exists in g5_oidc_identity. If any check fails, it clears the session keys and redirects immediately to /bbs/login.php.

All four live E2E scenarios against Keycloak 26.8.2 matched these rules:

  • Unlinked SSO blocked: Keycloak login returned to callback.php with iss and code, and Gnuboard5 returned HTTP 403.
  • Explicit link with password check: Wrong password returned HTTP 403; valid password redirected (302) with prompt=login and code_challenge_method=S256 and created g5_oidc_identity (mb_no=1).
  • Session reuse and live revocation: SSO login preserved /adm/ access (HTTP 200). After unlinking from a second session (action=unlink, 0 rows left), the next GET /index.php from the original SSO session immediately received HTTP 302 Location: .../bbs/login.php.

Logout branches cleanly via the member_logout_provider_url hook in bbs/logout.php. A standard local login redirects to the site home (http://127.0.0.1:18080). An OIDC session clears the local PHP session and redirects (302) to Keycloak’s end_session_endpoint with client_id and a same-origin-checked post_logout_redirect_uri (RP-Initiated Logout 1.0):

1
2
HTTP/1.1 302 Found
Location: http://127.0.0.1:18081/realms/gnuboard-dev/protocol/openid-connect/logout?client_id=gnuboard&post_logout_redirect_uri=http%3A%2F%2F127.0.0.1%3A18080%2F

Note: Back-Channel Logout is not implemented. If an administrator terminates a session or disables a user directly inside Keycloak, existing Gnuboard5 PHP sessions stay valid until they expire locally or the member is blocked or unlinked in Gnuboard5.

Encrypting admin OIDC secrets with AES-256-GCM AAD and optimistic locking

The plugin intentionally ignores G5_OIDC_ISSUER-style environment variables and treats g5_config.cf_oidc_settings—edited through the dedicated #foidcconfig form in adm/config_form.php (adm/oidc_config_update.php)—as the single source of truth.

Client secrets are never stored in plaintext. plugin/oidc/settings.php derives a 32-byte key from G5_TOKEN_ENCRYPTION_KEY using HKDF-SHA256 and encrypts the secret with AES-256-GCM, a 12-byte random IV, and issuer\0client_id\0discovery_url as Additional Authenticated Data (AAD):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// plugin/oidc/settings.php (excerpt)
function g5_oidc_secret_context($settings)
{
    $discovery = $settings['discovery_url'] ?: rtrim($settings['issuer'], '/') . '/.well-known/openid-configuration';
    return $settings['issuer'] . "\0" . $settings['client_id'] . "\0" . $discovery;
}

function g5_oidc_encrypt_secret($secret, $settings)
{
    $iv = random_bytes(12);
    $context = g5_oidc_secret_context($settings);
    $ciphertext = openssl_encrypt($secret, 'aes-256-gcm', g5_oidc_secret_key(), OPENSSL_RAW_DATA, $iv, $tag, $context);
    return base64_encode($iv . $tag . $ciphertext);
}

Binding the provider context as AAD solves two problems at once. When an admin updates only display_name or logo_url while keeping the same issuer, client ID, and discovery URL, they can leave the secret field blank and keep the existing ciphertext. If any of those three provider fields change—or get tampered with in the database—decryption fails immediately so a secret cannot be sent to a different endpoint. Writes also include a revision SHA-256 hash and WHERE BINARY cf_oidc_settings <=> ... (optimistic compare-and-swap), rejecting stale concurrent saves with a conflict warning.

Button branding uses logo_url URL validation rather than file upload. g5_oidc_valid_logo_url() accepts only site-relative paths starting with / (rejecting // and \) or https:// URLs without user/pass. Leaving it blank falls back to the default fa-key icon and SSO (or the configured display name). In local DB checks after saving, cf_oidc_settings.secret held only a Base64-encoded 52-byte binary blob (12B IV + 16B GCM tag + 24B ciphertext), and submitting an outdated revision failed with a settings-changed alert.

Gnuboard5 admin configuration panel showing the OIDC settings section Figure 2. adm/config_form.php#anc_cf_oidc in the isolated local stack (127.0.0.1:18080). Labels show status (현재 상태 사용 중, active), display name (사내 통합인증), logo_url guidance, split Frontchannel/Backchannel URLs, and a blank client secret field that preserves the stored ciphertext.

Verifying locally with Keycloak split endpoints and tests/oidc.php

Running a PHP web app and Keycloak together in Docker Compose hits a classic networking mismatch: the browser logs in at http://127.0.0.1:8081, whereas the PHP container cannot reach Keycloak on its own loopback interface and must call http://keycloak:8080. Hardcoding keycloak:8080 as the hostname breaks browser redirects; hardcoding 127.0.0.1:8081 breaks backchannel token and JWKS calls.

compose.yaml solves this with Keycloak 26.8.2 Hostname v2 (KC_HOSTNAME_BACKCHANNEL_DYNAMIC: "true") and --import-realm:

1
2
3
4
5
6
7
8
9
10
11
# compose.yaml (excerpt)
keycloak:
  image: quay.io/keycloak/keycloak:26.8.2
  command: ["start-dev", "--import-realm"]
  environment:
    KC_HOSTNAME: "http://127.0.0.1:${GNUBOARD_KEYCLOAK_PORT:-8081}"
    KC_HOSTNAME_BACKCHANNEL_DYNAMIC: "true"
    KC_HEALTH_ENABLED: "true"
    GNUBOARD_DEV_URL: "http://127.0.0.1:${GNUBOARD_WEB_PORT:-8080}"
  ports:
    - "127.0.0.1:${GNUBOARD_KEYCLOAK_PORT:-8081}:8080"

Querying the discovery document from inside the web container via http://keycloak:8080/realms/gnuboard-dev/.well-known/openid-configuration confirms that issuer, authorization_endpoint, and end_session_endpoint stay on the frontchannel (127.0.0.1), while token_endpoint and jwks_uri switch to keycloak:8080 (ports below show 18081 from an isolated test run; the default Compose port is 8081):

1
2
3
4
5
6
7
8
9
{
  "issuer": "http://127.0.0.1:18081/realms/gnuboard-dev",
  "authorization_endpoint": "http://127.0.0.1:18081/realms/gnuboard-dev/protocol/openid-connect/auth",
  "token_endpoint": "http://keycloak:8080/realms/gnuboard-dev/protocol/openid-connect/token",
  "jwks_uri": "http://keycloak:8080/realms/gnuboard-dev/protocol/openid-connect/certs",
  "end_session_endpoint": "http://127.0.0.1:18081/realms/gnuboard-dev/protocol/openid-connect/logout",
  "authorization_response_iss_parameter_supported": true,
  "code_challenge_methods_supported": ["plain", "S256"]
}

G5OidcProvider::validateUrl() enforces HTTPS by default. Setting G5_OIDC_ALLOW_HTTP_DEV=1 relaxes HTTP only for loopback hosts (127.0.0.1, localhost, [::1]) and the backchannel keycloak:8080 service. In local tests, unsetting the flag or passing an external HTTP host (http://evil.example.test) both threw OpenID Connect URLs require HTTPS. Because the local stack runs over HTTP, live TLS certificate verification (g5_curl_tls_verify) is outside the local test scope and must be verified on HTTPS staging before production rollout.

With Composer dependencies pre-installed at /opt/gnuboard/oidc/vendor/autoload.php, the regression suite runs in one command. Using a local 2048-bit RSA key pair, tests/oidc.php checks seven tampered ID token claims (iss, multi-aud, azp, expired exp, future iat, mismatched nonce, >255-char sub), foreign RSA keys, double-encoded open redirects, AES-256-GCM AAD tampering, logo_url rules, and ignoring env-var overrides:

1
2
$ docker compose exec -T web php tests/oidc.php
OIDC token, return URL and administrator settings tests passed

One practical quirk turned up during automated local testing: Keycloak 26.8.2 sets the Secure attribute on AUTH_SESSION_ID and KC_RESTART cookies even when sslRequired is "none". Browsers treat http://127.0.0.1 as a potentially trustworthy origin and send those cookies anyway, whereas non-browser HTTP clients like Python’s urllib need explicit loopback Secure-cookie handling if you script the login flow.

Before deploying this plugin to production, run through five checks:

  1. Enforce HTTPS: Confirm G5_OIDC_ALLOW_HTTP_DEV is unset in production and use https:// for every issuer, callback, discovery, and logout URL.
  2. Back up G5_TOKEN_ENCRYPTION_KEY: Rotating or losing this key breaks decryption of the stored client secret in cf_oidc_settings.
  3. Keep redirect URIs aligned: Whenever you change ports via .env or move to a production domain, update both /plugin/oidc/callback.php and the post-logout URI in the IdP client configuration.
  4. Document logout boundaries: Make clear in operational docs that Gnuboard5 logout triggers RP-Initiated Logout at the IdP, while IdP-initiated logout or user bans do not revoke active PHP sessions immediately without Back-Channel Logout.
  5. Gate upgrades with tests/oidc.php: Run php tests/oidc.php after any PHP or firebase/php-jwt upgrade and require exit code 0.

References

OpenID Connect Core 1.0 incorporating errata set 2
This document specifies a new parameter called iss. This parameter is used to explicitly include the issuer identifier of the authorization server in the authorization response of an OAuth authorization flow. The iss parameter serves as an effective countermeasure to "mix-up attacks".
Configure the frontend and backchannel endpoints exposed by Keycloak.
OpenID Connect RP-Initiated Logout 1.0
This post is licensed under CC BY 4.0 by the author.