PHP code example of saifulferoz / keycloak-admin-client

1. Go to this page and download the library: Download saifulferoz/keycloak-admin-client 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/ */

    

saifulferoz / keycloak-admin-client example snippets


use Feroz\KeycloakAdmin\KeycloakClient;
use Feroz\KeycloakAdmin\Model\User\UserRepresentation;
use Feroz\KeycloakAdmin\Query\UserQuery;

// 1. Instantiate client using the fluent builder
$client = KeycloakClient::builder()
    ->withBaseUrl('https://iam.example.com')
    ->withAuthRealm('master')
    ->withDefaultTargetRealm('mycompany')
    ->withClientCredentials('admin-cli', 'your-client-secret')
    ->build();

// 2. Manage Users
$users = $client->users(); // uses default target realm 'mycompany'

// Create a new user
$newUser = UserRepresentation::create('[email protected]', 'johndoe')
    ->withName('John', 'Doe')
    ->withEmailVerified(true)
    ->withAttribute('department', 'Engineering')
    ->withPassword('TemporaryP@ssword123!', temporary: true);

$userId = $users->create($newUser);

// Query users with pagination and search
$query = UserQuery::create()
    ->withSearch('john')
    ->withEnabled(true)
    ->withPagination(page: 1, perPage: 20);

$results = $users->list($query);
foreach ($results as $user) {
    echo $user->username . ' (' . $user->email . ')' . PHP_EOL;
}

// Reset password
$users->resetPassword($userId, 'NewSecretPassword123!');

// 3. Manage Roles & Groups
$client->users()->addRealmRoleMappings($userId, [
    $client->roles()->getRealmRole('admin')
]);