Keycloak PoW

Keycloak PoW Extension — adds computational PoW (proof-of-work) challenges to login, registration, and password-reset flows. Protects against bot spam and brute-force attacks by requiring clients to solve a light cryptographic puzzle before authenticating. Uses Argon2 (memory-hard, GPU-resistant) or SHA-256, with IP-adaptive difficulty that scales challenge hardness based on per-IP request patterns. Rate state is stored in Infinispan, enabling shared difficulty tracking across clustered Keycloak instances. Deploy as a standard Keycloak SPI plugin — works with any Keycloak 26.6 instance. Three-layer defense on every submission: 1. Honeypot — silently rejects bots that auto-fill all form fields 2. Solve-time validation — rejects submissions arriving faster than configured minimum (default 500ms) 3. Hash verification — verifies proof-of-work correctness and prevents nonce replay attacks

Moderate Pure Nim score 50/100 · last commit 2026-06-11 · 1 stars · tests present · no docs generated

Summary

Latest Version Unknown
License Unknown
CI Status Failing
Stars 1
Forks 0
Open Issues 0
Last Commit 2026-06-11
Downloads 0
Last Indexed 2026-11-24 09:10

Installation

nimble install Keycloak PoW
choosenim install Keycloak PoW
git clone https://gitlab.com/mrbuch/keycloak/keycloak-pow

OS Compatibility

Platform Linux macOS Windows FreeBSD OpenBSD NetBSD Android iOS WASM Embedded
Keycloak PoW ✓ ✓ ✓ - - - - - - -

README

Proof of Work Extension for Keycloak

Protects login, registration, and password-reset flows against bots and credential-stuffing attacks by requiring the browser to solve a memory-hard Argon2id challenge (or SHA-256) before submitting any form.

Compatibility

Component Version
Keycloak 26.6.1 (tested)
Java 21
Maven 3.9+

Using a different Keycloak version may require recompiling against matching keycloak-server-spi / keycloak-services artifacts. Update <keycloak.version> in pom.xml accordingly and re-test.


Installation

1. Build the JAR

./mvnw clean package -DskipTests

Output: target/keycloak-pow-1.0.0-SNAPSHOT.jar

2. Deploy to Keycloak

Copy the JAR into Keycloak's providers/ directory and restart:

cp target/keycloak-pow-1.0.0-SNAPSHOT.jar /opt/keycloak/providers/
/opt/keycloak/bin/kc.sh build   # only needed once after adding a new provider
/opt/keycloak/bin/kc.sh start

For local development with Docker:

docker run -p 8080:8080 \
  -v ./target/keycloak-pow-1.0.0-SNAPSHOT.jar:/opt/keycloak/providers/keycloak-pow.jar \
  quay.io/keycloak/keycloak:26.6.1 start-dev

Flow Configuration

Add the PoW execution to each flow you want to protect via Keycloak Admin Console → Authentication.

Important: Keycloak does not allow modifying built-in flows. You must duplicate the flow first, add the execution to the copy, and then bind the new flow to the realm.

Login flow

Target structure — PoW goes inside the forms subflow so Cookie/Kerberos can still bypass it:

browser-pow
├── Cookie                                   ALTERNATIVE
├── Kerberos                                 ALTERNATIVE
└── browser-pow forms                        ALTERNATIVE (subflow)
    ├── Proof of Work                        REQUIRED    ← add here
    └── Username Password Form               REQUIRED

Steps:

  1. Go to Authentication → Flows
  2. Click ⋮ next to browser → Duplicate → name it browser-pow
  3. Open the duplicated flow → expand browser-pow forms subflow
  4. Click Add execution inside the subflow
  5. Select Proof of Work → Add
  6. Drag it above Username Password Form and set requirement to Required
  7. Click the ⚙️ gear icon to configure difficulty (optional — defaults apply if skipped)
  8. Go to Authentication → Bindings → set Browser flow to browser-pow → Save

Registration flow

Target structure — PoW goes as a sub-step of Registration Form so the nonce is injected into the same form:

registration-pow
└── registration-pow form                    ALTERNATIVE (subflow)
    └── Registration Form                    REQUIRED
        ├── Proof of Work Validation              REQUIRED    ← add here
        └── Registration User Profile Creation    REQUIRED

Steps:

  1. Go to Authentication → Flows
  2. Click ⋮ next to registration → Duplicate → name it registration-pow
  3. Open the duplicated flow → expand Registration Form
  4. Click Add execution inside Registration Form
  5. Select Proof of Work Validation → Add
  6. Drag it to the top (above Registration User Profile Creation) and set requirement to Required
  7. Go to Authentication → Bindings → set Registration flow to registration-pow → Save

Password reset flow

Target structure — PoW goes at the top of the flow, before the user submits their email:

reset-credentials-pow
├── Proof of Work                            REQUIRED    ← add here
├── Choose User                              REQUIRED
├── Send Reset Email                         REQUIRED
└── Reset Credentials Handler               REQUIRED
    └── Reset Password                       REQUIRED

Steps:

  1. Go to Authentication → Flows
  2. Click ⋮ next to reset credentials → Duplicate → name it reset-credentials-pow
  3. Open the duplicated flow → Add execution
  4. Select Proof of Work → Add
  5. Drag it to the very top (above Choose User) and set requirement to Required
  6. Click the ⚙️ gear icon to configure difficulty (optional — defaults apply if skipped)
  7. Go to Authentication → Bindings → set Reset credentials flow to reset-credentials-pow → Save

Internationalization (i18n)

All user-facing strings in the PoW modal and the verification-failed error banner are translated automatically based on the active Keycloak locale.

Bundled languages

Code Language
en English (baseline — always available, no configuration needed)
de German
ja Japanese
hi Hindi

Enabling additional locales (admin steps)

English works out of the box with no configuration. To activate other bundled languages:

  1. Realm Settings → Localization
  2. Toggle Internationalization Enabled → ON
  3. Add the desired locales (de, ja, hi) to Supported Locales
  4. Set a Default Locale
  5. Save — no restart required

Keycloak selects the locale per request from the user's browser Accept-Language header or an explicit ?kc_locale=<code> query parameter.

Adding a new language

Drop a messages_<lang>.properties file into src/main/resources/theme-resources/messages/ using the same keys as messages_en.properties, rebuild the JAR, and redeploy. No Java changes required.

# Example: messages_fr.properties
pow.verifying=Vérification en cours
pow.verified=Vérifié
pow.failed=Échec de la vérification
pow.cancelled=Annulé
pow.computing=calcul de la preuve de travail
pow.success=succès
pow.retry=veuillez réessayer
pow.cancelledStatus=annulé
pow.credit=fait avec ♥ par Mr.Buch
pow.branding=Propulsé par Keycloak
powVerificationFailed=La vérification de la preuve de travail a échoué. Veuillez réessayer.

Theme Integration & Customization

The extension ships FreeMarker resources served automatically from the JAR via ThemeResourceProvider — no theme inheritance or file copying required.

UI Modes: Modal (default) renders built-in overlay and spinner. Headless mode (custom) disables built-in UI; use headless=true and implement your own styling by listening to pow:status CustomEvents. See sample-theme/ for Brave PoW card-style example.

Resource Purpose
pow.ftl Core macro that injects hidden inputs + JS solver into any form
pow-login.ftl Standalone challenge page rendered by PowAuthenticator for login and password-reset flows
pow-base.ftl Shared base template for login and reset flows; optional for headless customization

Registration (register.ftl)

Registration uses PowFormAction, which injects the nonce into the existing form. Add two lines to register.ftl:

<#import "pow.ftl" as pow>

<form id="kc-register-form" action="${url.loginAction}" method="post">
    <!-- your existing fields -->
    <@pow.fields formId="kc-register-form"/>
</form>

The macro injects the hidden nonce/solution inputs and the JS solver. By default, a modal shows on page load and dismisses once solved. If the user submits before solving completes, the modal reappears and holds the submission.

For headless mode (custom UI), pass headless=true:

<@pow.fields formId="kc-register-form" headless=true/>

The macro emits pow:status CustomEvents; implement custom styles and UI responses to those events. See sample-theme/custom-pow-theme/login/pow-register.ftl for an example.

Login and Password-reset (login.ftl, login-reset-password.ftl)

These flows use PowAuthenticator, which renders a separate pow-login.ftl page before the login or reset form. The PoW is verified in that step; by the time the login/reset form renders, PoW is already complete. Do not add <@pow.fields> to these templates.

To customize with headless mode, override pow-login.ftl in your theme and use headless=true:

<@pow.fields formId="pow-challenge-form" autoSubmit=true headless=true/>

Listen to pow:status events and implement custom UI. A Brave PoW card-inspired example is in sample-theme/custom-pow-theme/login/pow-login.ftl.


Configuration Reference

Each flow execution can be configured independently in the Admin Console (gear icon on the execution). All fields accept environment variable fallbacks. Argon2 and SHA-256 are configured independently — changing one algorithm's settings does not affect the other.

Common

Admin UI Field Env Var Default Description
Hash Algorithm POW_HASH_ALGORITHM argon2 argon2 (memory-hard, GPU-resistant, recommended) or sha256 (fast, no WASM required)
Trusted Proxy Count POW_TRUSTED_PROXIES 0 Number of trusted reverse proxies in front of Keycloak — see below

Argon2 Config

Argon2 is memory-hard by design — each attempt costs ~16 MB RAM and ~100–300 ms in browser WASM. There is no minimum solve time setting; the memory-hard computation is the proof of work.

Admin UI Field Env Var Default Description
Argon2 — Base Difficulty (bits) POW_ARGON2_BASE_DIFFICULTY 1 Leading zero bits required at low request rates
Argon2 — Max Difficulty (bits) POW_ARGON2_MAX_DIFFICULTY 4 Cap for high-rate IPs (4 bits ≈ 16 attempts ≈ 2–5 s)
Argon2 — Rate Threshold POW_ARGON2_RATE_THRESHOLD 10 Requests per window before difficulty steps up
Argon2 — Difficulty Step (bits) POW_ARGON2_DIFFICULTY_STEP 1 Bits added per threshold multiple exceeded
Argon2 — Rate Window (seconds) POW_ARGON2_WINDOW_SECONDS 60 Sliding window for per-IP request counting
Argon2 — Challenge TTL (seconds) POW_ARGON2_CHALLENGE_TTL 300 How long a nonce stays valid before expiring
Argon2 — Memory (KB) POW_ARGON2_MEMORY_KB 16384 Memory cost per attempt; higher = more GPU-resistant
Argon2 — Iterations POW_ARGON2_ITERATIONS 1 Time cost (iteration count); 1 is sufficient at 16 MB

SHA-256 Config

SHA-256 is fast (~10 GH/s on GPU), so higher bit-difficulty and a minimum solve time are required to prevent pre-computed attacks.

Admin UI Field Env Var Default Description
SHA-256 — Base Difficulty (bits) POW_SHA256_BASE_DIFFICULTY 16 Leading zero bits required at low request rates
SHA-256 — Max Difficulty (bits) POW_SHA256_MAX_DIFFICULTY 24 Cap for high-rate IPs (24 bits ≈ 16 M hashes)
SHA-256 — Rate Threshold POW_SHA256_RATE_THRESHOLD 10 Requests per window before difficulty steps up
SHA-256 — Difficulty Step (bits) POW_SHA256_DIFFICULTY_STEP 2 Bits added per threshold multiple exceeded
SHA-256 — Rate Window (seconds) POW_SHA256_WINDOW_SECONDS 60 Sliding window for per-IP request counting
SHA-256 — Challenge TTL (seconds) POW_SHA256_CHALLENGE_TTL 300 How long a nonce stays valid before expiring
SHA-256 — Min Solve Time (ms) POW_SHA256_MIN_SOLVE_MS 500 Minimum ms between challenge issue and submission; faster = pre-computed rejection

Trusted Proxy Count

This field controls how the client IP is determined, which drives adaptive difficulty scaling.

Default (0) — safest, works for direct deployments: Proxy headers (X-Forwarded-For, X-Real-IP) are ignored entirely. The TCP remote address is used as the client IP. This prevents any IP spoofing via client-controlled headers.

Behind a reverse proxy (nginx, Caddy, AWS ALB, etc.): Set this to the number of trusted proxy hops between the internet and Keycloak. The extension reads the Nth-from-right token in X-Forwarded-For, which is the value appended by your outermost trusted proxy — not the client-supplied leftmost value.

Deployment Setting
Keycloak directly on internet (no proxy) 0
Single reverse proxy (nginx → Keycloak) 1
CDN or load balancer + reverse proxy (CDN → nginx → Keycloak) 2

Security note: Do not set this higher than the actual number of trusted proxies you control. Overestimating lets a client push a spoofed IP into the trusted position, making all requests appear to come from a fresh IP and defeating adaptive difficulty scaling.

Difficulty guide

Argon2 (default — memory-hard, GPU-resistant):

Difficulty (bits) Avg attempts Typical browser solve time
1 ~2 200–600 ms
2 ~4 400 ms – 1.2 s
3 ~8 800 ms – 2.4 s
4 ~16 1.6 – 5 s

Each attempt runs Argon2id with the configured memory and iteration parameters. GPU/ASIC parallelism is suppressed by the memory requirement.

SHA-256 (fallback — fast per-attempt, exponential search):

Difficulty (bits) Avg hashes to solve Typical browser solve time
16 ~65,000 < 1 second
20 ~1,000,000 1–3 seconds
24 ~16,000,000 5–15 seconds

How It Works

  1. When a user loads a protected page, Keycloak generates a random nonce and computes the required difficulty for that IP. Per-IP request counts are stored in Keycloak's shared object store, so adaptive difficulty is consistent across all nodes in a cluster. A honeypot field is injected invisibly; bots that auto-fill all inputs are silently rejected before the hash check.
  2. A full-page modal overlay appears immediately, showing "Verifying your browser…" while the JS solver searches for a counter X such that H(X, nonce) has at least N leading zero bits, where H is the configured algorithm. With Argon2 (default), each attempt is memory-hard (~16 MB, ~200 ms) making GPU parallelism ineffective. With SHA-256 (fallback), the solver yields every 500 iterations to keep the UI responsive.
  3. Once solved, the modal dismisses. For login and password-reset flows the form auto-submits; for registration the solution sits in a hidden field ready for the user's manual submit.
  4. Keycloak verifies the hash server-side (using the same algorithm and parameters that were issued with the challenge), checks that the elapsed solve time exceeds the configured minimum, and consumes the nonce (preventing replay).

Failure scenarios

Cause What happens
Solution hash does not meet difficulty Form is re-rendered with a fresh nonce and a powVerificationFailed error message. The user must solve the new challenge before resubmitting.
Nonce expired (TTL elapsed) Same as above — the stored nonce is gone, verification fails, and a new challenge is issued.
Nonce replayed (submitted twice) Rejected. SingleUseObjectProvider removes the nonce on first consumption; a second submission finds nothing to verify against.
JS disabled / bot skips the solver The pow_solution field is empty or missing, verification fails immediately, and a fresh challenge is issued.

PoW failures are reported as GENERIC_AUTHENTICATION_ERROR, not INVALID_CREDENTIALS, so they do not increment the brute-force counter or trigger account lockouts. Only a subsequent wrong password (in the password authenticator step) triggers brute-force protection.

Legitimate users with a modern browser experience no visible friction at the default difficulty. Bots that skip the JS step or submit without solving will be rejected.

CI/CD Pipeline

The GitLab CI pipeline (.gitlab-ci.yml) has two stages:

Stage What it does
build Compiles JAR, uploads to GitLab Package Registry, extracts release notes from CHANGELOG.md
release Creates GitLab Release with tag and asset link pointing to Package Registry

POM.xml Dependencies

The pipeline reads values directly from pom.xml — no hardcoded values:

CI Variable POM Source Example
RELEASE_VERSION project.version 1.0.0
ARTIFACT_ID project.artifactId keycloak-client-webhook
JAR_FILE target/${ARTIFACT_ID}.jar (resolved from project.artifactId) target/keycloak-client-webhook.jar

Package Registry URL pattern:

$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/$ARTIFACT_ID/v$RELEASE_VERSION/$ARTIFACT_ID.jar

Release tag is v$RELEASE_VERSION (e.g. v1.0.0). To release a new version, bump <version> in pom.xml and push to main.