PHP code example of sandstorm / keycloak-admin-api

1. Go to this page and download the library: Download sandstorm/keycloak-admin-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sandstorm / keycloak-admin-api example snippets


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']),
);

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…}