Keycloak SDK for Rust
An async Keycloak SDK for Rust — OIDC/OAuth2 authentication with hardened JWT validation plus the Admin REST API, behind a single facade.
Part of a nine-language polyglot SDK (Java · Python · Node · Go · C# · PHP · Rust · Ruby · Kotlin) whose concepts, layering and flows are isomorphic across every language — monorepo: https://github.com/xzawed/KeyCloakSDK
1.1.2is on crates.io — a patch release on top of1.1.1;1.0.0was the first release that carries the stability guarantee (a breaking change to the public API requires a major bump). The barecargo add keycloak-sdkbelow resolves1.1.2, and a hand-writtenkeycloak-sdk = "1"orkeycloak-sdk = "1.0"matches it too. Fixed: with the expected audience overridden throughwith_expected_audience(…), a code exchange with a nonce (exchange_code,exchange_code_with_redirect) failed — the id_token was validated against the access token's expected audience, so a genuine id_token naming the client id was refused withinvalid id_token … audience mismatch. The id_token'saudis now checked for the client id (OIDC Core §2, §3.1.3.7), so that exchange passes, and an id_token without the client id is refused even when itsaudequals the override;validate()still applies the override to access tokens. The JWKS cache, refetch limit and cold-failure backoff are shared by both paths. No public API changed.
Requirements
- Rust 1.88+ (MSRV — required by edition 2024 and let-chains)
- A tokio runtime — the SDK is async-only
- A Keycloak server (verified against 26.6)
Install
The SDK does not re-export a runtime: tokio is your dependency, not a transitive one, so the quickstart below does not compile without that second line.
Quickstart
The same three steps as every sibling SDK — get a token, verify it, call the Admin API.
use UserRepresentation;
use ;
async
A stock realm does not put the client id in a client-credentials token's aud, so step 2 fails until the
audience matches: either add an Audience protocol mapper to the client in Keycloak, or chain
.with_expected_audience("…") onto the config with the value your tokens actually carry (the API/resource
name, when the token is audienced at a resource server).
Errors are values, not panics: every fallible call returns Result<T, KeycloakError>, whose variants are
Config · Auth · Transport · Admin · TokenValidation.
The Admin representation types (UserRepresentation, ClientRepresentation, RealmRepresentation,
RoleRepresentation, GroupRepresentation) are re-exported from keycloak_sdk::types, so the keycloak
crate does not need to be a direct dependency of your project.
Security defaults
- Algorithm pinning — only the configured signature algorithms are accepted (default
RS256); the header'salgis never trusted, andalg: noneis structurally impossible:jsonwebtoken'sAlgorithmenum has nononevariant, so such a header fails to deserialize before any key is looked up. - Strict claim checks — exact
issmatch,audcontainment (againstexpected_audience, the client id by default; the id_token of a nonce-checked code exchange is always checked against the client id), mandatoryexp,nbfverified, and a bounded clock skew (30s by default). - DoS-safe JWKS — keys are cached, a refetch is triggered only by an unresolved
kidand never by a bad signature, and it is rate-limited to a minimum interval (with_jwks_min_refetch_secs, 30s by default). The gate is stamped when the refetch is decided, not when it succeeds, so an IdP outage cannot reopen it — so once the key set has been fetched, no volume of forgedkids makes the SDK issue more than one JWKS request per interval. A failed fetch is bounded separately: consecutive failures back off exponentially (0.2s, doubling, capped at 5s, with jitter), and inside that window the SDK fails fast without contacting the IdP. So a cold cache during an IdP outage no longer turns every validation into a request (measured: 20 attempts → 1 request, down from 20). Concurrent first validations collapse to a single fetch as well (measured: 20 concurrent → 1). ⚠️ The SDK never sleeps — it returns the error immediately, so retry pacing stays the caller's decision. - Safe transport — TLS verification on by default (rustls), redirects disabled entirely (SSRF hardening), and secrets/tokens masked as
***in the SDK'sDebugoutput.
Masking covers the SDK's own Debug impls; it cannot cover what your logging framework or a panic message does with a value you hand it.
Versioning and support
This SDK is 1.0 and follows SemVer: a breaking change to the public API requires a major bump. That promise is machine-backed — CI diffs this lane's public API against the previously published artifact on every build (cargo-semver-checks), and a removal or an incompatible change fails the build. ⚠️ The gate compares the API surface. A change that leaves the surface identical but alters behaviour is not caught by it, so read the release notes before upgrading.
Only the newest released version of each language SDK receives security fixes; there are no long-term-support lines and older releases are not backported to.
Each of the nine languages versions independently. All nine reached 1.0.0 in the same release wave because they earned the same guarantee at the same time — they do not move in lockstep afterwards.
Documentation
- Project overview — all nine languages, what is identical and what is not
- Changelog — read this before upgrading; breaking changes are listed per language
- Getting started — install and quickstart for this language
- Compatibility — which Keycloak server range and base libraries each published version shipped against
- Deploying a Keycloak server
- Full runnable example
- Security policy