sandstorm / keycloak-admin-api
Framework-agnostic PHP client for the Keycloak Admin REST API (users, groups, credentials, sessions, events), returning immutable typed DTOs and collections.
Requires
- php: ^8.3
- ext-json: *
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-message: ^1.1 || ^2.0
Requires (Dev)
- guzzlehttp/guzzle: ^7.3
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.0
Suggests
- guzzlehttp/guzzle: A PSR-18 HTTP client and PSR-17 factories (^7.3) that satisfy this library's transport seam; any PSR-18/PSR-17 implementation works.
README
A framework-agnostic PHP client for the Keycloak Admin REST API (target: Keycloak 26.5 or newer).
The whole package is work in progress, and is extended as needed.
Thanks to BroodfondsMakers for sponsoring the development of this package, and for agreeing to Open Source it!
It exposes the admin API in modern PHP, using immutable typed DTOs and collections. It has no framework coupling.
- sandstorm/keycloak-admin-api
Requirements
- PHP 8.3+
- A PSR-18 HTTP client, like Guzzle
Usage
use GuzzleHttp\Client; use GuzzleHttp\Psr7\HttpFactory; use Sandstorm\KeycloakAdminApi\Connection\Auth\ServiceAccountTokenProvider; use Sandstorm\KeycloakAdminApi\Connection\KeycloakSettings; use Sandstorm\KeycloakAdminApi\Connection\KeycloakSettingsProvider; use Sandstorm\KeycloakAdminApi\Connection\KeycloakTransport; use Sandstorm\KeycloakAdminApi\Features\KeycloakUsersApi\KeycloakUsersApiImplementation; use Sandstorm\KeycloakAdminApi\SharedModel\KeycloakUserId; $settings = new class implements KeycloakSettingsProvider { public function get(): KeycloakSettings { return new KeycloakSettings('https://keycloak.example', 'my-realm', 'admin-api', $secret); } }; // Any PSR-18 client + PSR-17 factories work; here Guzzle provides both. Inject a client that never // body-logs - admin responses carry user PII. $client = new Client(); $httpFactory = new HttpFactory(); // PSR-17 request + stream factory $transport = new KeycloakTransport( $settings, $client, $httpFactory, $httpFactory, new ServiceAccountTokenProvider($settings, $client, $httpFactory, $httpFactory), ); $users = new KeycloakUsersApiImplementation($transport); foreach ($users->list(search: 'jane', first: 0, max: 20, enabled: true) as $user) { echo $user->username, ' ', $user->fullName() ?? '', PHP_EOL; } // Update: read-modify-write. Fetch the full user, apply edits with the immutable `with*()` mutators, // then PUT it back. toRepresentation() overlays only the edited fields onto the original response, so // any Keycloak field this DTO does not model round-trips untouched (never clobbered). $user = $users->getById(new KeycloakUserId('β¦')); $users->update( $user->withFirstName('Janet') ->withEnabled(false) ->withEmailVerified(true) ->withAttribute('nickname', ['J']), );
Also on KeycloakUsersApi:
findByUsername(string): ?KeycloakUser- exact identity lookup (exact=true), full representation; more than one match is refused, never silently picked from.create(CreateKeycloakUserCommand): KeycloakUser-POST /users(attributes, credentials, required actions), returned read back through the API.KeycloakUser::withCredentials()+update()- replace all stored credentials of an existing user.
Keycloak REST API coverage
This is based on the Keycloak Admin REST API: The vast majority is not implemented, because so far this is focused upon user-administration.
Legend: β implemented Β· π‘ partial Β· β not implemented (candidate)
| # | KC resource group | Status | What we cover / our slice |
|---|---|---|---|
| 1 | Attack Detection | β | brute-force status/clear - none |
| 2 | Authentication Management | β | realm auth-flow config |
| 3 | Client Attribute Certificate | β | client keystores |
| 4 | Client Initial Access | β | dynamic client registration tokens |
| 5 | Client Registration Policy | β | - |
| 6 | Client Role Mappings | β | a user's client-role grants - candidate |
| 7 | Client Scopes | β | - |
| 8 | Clients | π‘ | GET /clients (KeycloakClientsApi::list); client CRUD - β |
| 9 | Component | β | user-federation / key providers |
| 10 | default (realm root) | β | GET/PUT /admin/realms/{realm} - planned KeycloakRealmApi |
| 11 | Groups | π‘ | GET /groups (KeycloakGroupsApi::listRealmGroups); group CRUD, /groups/{id}/members, children - β |
| 12 | Identity Providers | β | - |
| 13 | Key | β | realm keys |
| 14 | Organizations | β | - |
| 15 | Protocol Mappers | β | - |
| 16 | Realms Admin | π‘ | GET /events, GET /admin-events (KeycloakEventsApi); realm config + /health - β (planned KeycloakRealmApi) |
| 17 | Role Mapper | β | a user's realm-role grants - candidate |
| 18 | Roles | β | realm/client role definitions |
| 19 | Roles (by ID) | β | - |
| 20 | Scope Mappings | β | - |
| 21 | Users | π‘ | read + update + user-profile schema + credentials + sessions + membership (see detail below); create/delete/reset-password and many sub-resources - β |
| 22 | Workflows | β | - |
| - | OIDC token endpoint | β | POST /realms/{realm}/protocol/openid-connect/token - ServiceAccountTokenProvider |
#21 - Users (paths under /admin/realms/{realm})
| Method & path | Status | Notes |
|---|---|---|
GET /users |
β | KeycloakUsersApi::list (infix search), ::findByUsername (exact=true) |
POST /users |
β | KeycloakUsersApi::create (read back by exact username) |
GET /users/count |
β | KeycloakUsersApi::count |
GET /users/profile |
β | KeycloakRealmApi::getUserProfile (attribute schema + per-role perms) |
PUT /users/profile |
β | user-profile schema authoring |
GET /users/profile/metadata |
β | user-profile metadata (drives proactive form rendering) |
GET /users/{user-id} |
β | KeycloakUsersApi::getById |
PUT /users/{user-id} |
β | KeycloakUsersApi::update (lossless read-modify-write; also writes replacement credentials) |
DELETE /users/{user-id} |
β | user deletion |
GET /users/{user-id}/configured-user-storage-credential-types |
β | - |
GET /users/{user-id}/consents |
β | - |
DELETE /users/{user-id}/consents/{client} |
β | - |
GET /users/{user-id}/credentials |
β | KeycloakCredentialsApi::get |
DELETE /users/{user-id}/credentials/{credentialId} |
β | KeycloakCredentialsApi::delete |
POST /users/{user-id}/credentials/{credentialId}/moveAfter/{newPreviousCredentialId} |
β | reorder credential |
POST /users/{user-id}/credentials/{credentialId}/moveToFirst |
β | reorder credential |
PUT /users/{user-id}/credentials/{credentialId}/userLabel |
β | rename credential |
PUT /users/{user-id}/disable-credential-types |
β | - |
PUT /users/{user-id}/execute-actions-email |
β | KeycloakCredentialsApi::executeActionsEmail (array body) |
GET /users/{user-id}/federated-identity |
β | - |
POST /users/{user-id}/federated-identity/{provider} |
β | - |
DELETE /users/{user-id}/federated-identity/{provider} |
β | - |
GET /users/{user-id}/groups |
β | KeycloakGroupsApi::getUserGroups |
GET /users/{user-id}/groups/count |
β | - |
PUT /users/{user-id}/groups/{groupId} |
β | KeycloakGroupsApi::addUserToGroup (body-less) |
DELETE /users/{user-id}/groups/{groupId} |
β | KeycloakGroupsApi::removeUserFromGroup |
POST /users/{user-id}/impersonation |
β | deliberately not supported: it plants an SSO cookie in the browser (so a server-side call is useless), and it backchannel-logs-out the caller's own session when caller and target share a realm. |
POST /users/{user-id}/logout |
β | KeycloakSessionsApi::logoutAll |
GET /users/{user-id}/offline-sessions/{clientUuid} |
β | - |
PUT /users/{user-id}/reset-password |
β | not needed: KeycloakUser::withCredentials() + update covers the admin-set / pre-hashed case; execute-actions-email preferred |
PUT /users/{user-id}/reset-password-email |
β | deprecated alias of execute-actions-email |
PUT /users/{user-id}/send-verify-email |
β | |
GET /users/{user-id}/sessions |
β | KeycloakSessionsApi::getSessions |
GET /users/{user-id}/unmanagedAttributes |
β | - |
#11 - Groups (paths under /admin/realms/{realm})
| Method & path | Status | Notes |
|---|---|---|
GET /groups |
β | KeycloakGroupsApi::listRealmGroups |
POST /groups |
β | group CRUD |
GET /groups/count |
β | - |
GET /groups/{group-id} |
β | single group |
PUT /groups/{group-id} |
β | group CRUD |
DELETE /groups/{group-id} |
β | group CRUD |
GET /groups/{group-id}/children |
β | sub-group listing |
POST /groups/{group-id}/children |
β | sub-group create |
GET /groups/{group-id}/members |
β | list users in a group (group-filter data source) |
GET /groups/{group-id}/management/permissions |
β | FGAP admin permissions |
PUT /groups/{group-id}/management/permissions |
β | FGAP admin permissions |
#8 - Clients (paths under /admin/realms/{realm})
| Method & path | Status | Notes |
|---|---|---|
GET /clients |
β | KeycloakClientsApi::list β the realm's applications; KeycloakClients::browserLoginable() filters to the browser-loginable ones, KeycloakClient::resolvedUrl() yields an openable URL (rootUrl/baseUrl join, ${authBaseUrl}/${authAdminUrl} substitution, redirect-URI origin fallback) |
GET /clients/{id} |
β | single client |
POST /clients |
β | client CRUD |
PUT /clients/{id} |
β | client CRUD |
DELETE /clients/{id} |
β | client CRUD |
#16 - Realms Admin (paths under /admin/realms)
| Method & path | Status | Notes |
|---|---|---|
GET / |
β | list realms |
POST / |
β | create realm |
GET /{realm} |
β | realm config (editUsernameAllowed, events flags) - planned KeycloakRealmApi |
PUT /{realm} |
β | realm config authoring |
DELETE /{realm} |
β | delete realm |
GET /{realm}/admin-events |
β | KeycloakEventsApi::getAdminEventsForUser |
DELETE /{realm}/admin-events |
β | clear admin events |
POST /{realm}/client-description-converter |
β | - |
GET /{realm}/client-policies/policies |
β | - |
PUT /{realm}/client-policies/policies |
β | - |
GET /{realm}/client-policies/profiles |
β | - |
PUT /{realm}/client-policies/profiles |
β | - |
GET /{realm}/client-session-stats |
β | - |
GET /{realm}/client-types |
β | - |
PUT /{realm}/client-types |
β | - |
GET /{realm}/credential-registrators |
β | - |
GET /{realm}/default-default-client-scopes |
β | - |
PUT /{realm}/default-default-client-scopes/{clientScopeId} |
β | - |
DELETE /{realm}/default-default-client-scopes/{clientScopeId} |
β | - |
GET /{realm}/default-groups |
β | - |
PUT /{realm}/default-groups/{groupId} |
β | - |
DELETE /{realm}/default-groups/{groupId} |
β | - |
GET /{realm}/default-optional-client-scopes |
β | - |
PUT /{realm}/default-optional-client-scopes/{clientScopeId} |
β | - |
DELETE /{realm}/default-optional-client-scopes/{clientScopeId} |
β | - |
GET /{realm}/events |
β | KeycloakEventsApi::getUserEvents |
DELETE /{realm}/events |
β | clear login events |
GET /{realm}/events/config |
β | events flags |
PUT /{realm}/events/config |
β | events config authoring |
GET /{realm}/group-by-path/{path} |
β | candidate |
GET /{realm}/localization |
β | realm i18n |
GET /{realm}/localization/{locale} |
β | realm i18n |
POST /{realm}/localization/{locale} |
β | realm i18n |
DELETE /{realm}/localization/{locale} |
β | realm i18n |
GET /{realm}/localization/{locale}/{key} |
β | realm i18n |
PUT /{realm}/localization/{locale}/{key} |
β | realm i18n |
DELETE /{realm}/localization/{locale}/{key} |
β | realm i18n |
POST /{realm}/logout-all |
β | |
POST /{realm}/partial-export |
β | - |
POST /{realm}/partialImport |
β | - |
POST /{realm}/push-revocation |
β | - |
DELETE /{realm}/sessions/{session} |
β | |
POST /{realm}/testSMTPConnection |
β | realm SMTP config |
GET /{realm}/users-management-permissions |
β | FGAP admin permissions |
PUT /{realm}/users-management-permissions |
β | FGAP admin permissions |
Development Ideas
Package layout (feature-first)
src/
Connection/ transport + auth
Auth/
SharedModel/ KeycloakUserId, KeycloakTimestamp, KeycloakCollection (core value objects)
Features/
KeycloakUsersApi.php + KeycloakUsersApi/{β¦Implementation, Dto/β¦}
KeycloakGroupsApi.php + KeycloakGroupsApi/{β¦}
KeycloakCredentialsApi.php + KeycloakCredentialsApi/{β¦}
KeycloakSessionsApi.php + KeycloakSessionsApi/{β¦}
KeycloakClientsApi.php + KeycloakClientsApi/{β¦Implementation, Dto/KeycloakClient(s)}
KeycloakEventsApi.php + KeycloakEventsApi/{β¦}
KeycloakRealmApi.php + KeycloakRealmApi/{β¦Implementation, Dto/KeycloakUserProfileβ¦}
Each feature keeps its interface, implementation, and DTOs together. Interfaces carry the Keycloak
prefix so an imported symbol is self-describing inside a larger host codebase.
Unit and Integration Tests
mise run install # composer install mise run test # unit suite - no I/O, no Keycloak mise run analyse # phpstan (level 6)
Two tiers:
- Unit (
tests/Unit) - fast, hermetic. Real logic only (DTO/collection parsing tolerance, token cache, array-body encoding, query building, the non-2xx βUnexpectedKeycloakResponseException(withstatusCode) mapping) driven through a PSR-18 mock. - Integration / E2E (
tests/Integration) - runs the client against a real Keycloak 26.5.3 in Docker (tests/Integration/docker-compose.ymlimports two self-contained realms). This proves the wire contract unit tests cannot. The write suite (KeycloakUserWritesE2ETest) creates uniquely named users and proves a written credential by really logging in with it, so it is re-runnable against a long-lived instance.
mise run e2e # boot Keycloak (both realms), run the integration suite, tear down # or step by step: mise run e2e:up mise run test:integration mise run e2e:down
Log into the Keycloak admin console at http://localhost:9911 with admin / admin. Seeded users all
have password changeit.
Two realms are imported so the wire contract is proven in both authorization modes β classic
realm-management roles and Fine-Grained Admin Permissions (FGAP). The FGAP realm drives the
caller-relative access map (KeycloakUser::$access) and per-caller write authorisation: a user bearer is
obtained via the public e2e-login direct-grant client (tests/Support/DirectGrantTokenProvider), so calls run
as that user and Keycloak evaluates that user's own grants.
| Realm | Admin Permissions (FGAP) | Notable seeded users / caller identity |
|---|---|---|
test-realm |
off (classic roles) | service account (admin-api, realm-management roles), login-user (none), jane in /staff |
test-realm-fgap |
on | admin-user (roles), login-user (none), sarah + jane in /staff, emma in /endusers |
FGAP staff policy (baked into realm-import-fgap.json)
Staff read everyone, edit endusers, can't touch other staff:
match-staff = Group policy β members of /staff
β
ββββββββββββββ΄ββββββββββββββββββββββββββββββ
βΌ βΌ
"staff can view all" "staff can manage endusers"
Users Β· view Β· All users Groups Β· manage-members Β· group /endusers
β β
βΌ βΌ
sarah ββviewβββΆ everyone sarah ββmanageβββΆ emma (β/endusers) β
sarah ββmanageβββΆ jane (β/staff) β 403
License
MIT