nti/keycloak-client

Connect to keycloak admin api easily

0.0.5 2023-09-21 12:56 UTC

This package is auto-updated.

Last update: 2024-10-21 15:15:58 UTC


README

Latest Version

Total Downloads

Donate

Introduction

This is a php client to connect to keycloak admin rest apis with no headache.

Features:

  1. Easy to use
  2. No need to get token or generate it - it's already handled by the client
  3. No need to specify any urls other than the base uri
  4. No encode/decode for json just data as you expect

Works with Keycloak 7.0+ admin REST API.

https://www.keycloak.org/documentation -> "Administration REST API"

How to use

1. Create new client

$client = NTI\KeycloakClient\Admin\KeycloakClient::factory([
    'realm' => 'master',
    'username' => 'admin',
    'password' => '1234',
    'client_id' => 'admin-cli',
    'client_secret' => 'sfdasd',
    'baseUri' => 'http://127.0.0.1:8180',
]);

Since version 0.30, if your Keycloak base URL starts with auth/, add it to baseUri (e.g. http://127.0.0.1:8180/auth). Base URL for Keycloak versions 7 to 16 have systematically auth/. On Keycloak 17+ it depends on your settings.

2. Use it

$client->getUsers();

//Result
// Array of users
/*
[
     [
       "id" => "39839a9b-de08-4d2c-b91a-a6ce2595b1f3",
       "createdTimestamp" => 1571663375749,
       "username" => "admin",
       "enabled" => true,
       "totp" => false,
       "emailVerified" => false,
       "disableableCredentialTypes" => [
         "password",
       ],
       "requiredActions" => [],
       "notBefore" => 0,
       "access" => [
         "manageGroupMembership" => true,
         "view" => true,
         "mapRoles" => true,
         "impersonate" => true,
         "manage" => true,
       ],
     ],
   ]
*/

$client->getUser([
    'id' => '39839a9b-de08-4d2c-b91a-a6ce2595b1f3'
]);

$client->createUser([
    'username' => 'test',
    'email' => 'test@test.com',
    'enabled' => true,
    'credentials' => [
        [
            'type'=>'password',
            'value'=>'1234',
        ],
    ],
]);

$client->updateUser([
    'id' => '39839a9b-de08-4d2c-b91a-a6ce2595b1f3',
    'username' => 'test',
    'email' => 'test@test.com',
    'enabled' => true,
    'credentials' => [
        [
            'type'=>'password',
            'value'=>'1234',
        ],
    ],
]);

$client->deleteUser([
    'id' => '39839a9b-de08-4d2c-b91a-a6ce2595b1f3'
]);

Customization

Supported credentials

It is possible to change the credential's type used to authenticate by changing the configuration of the keycloak client.

Currently, the following credentials are supported

  • password credentials, used by default
    • to authenticate with a user account
    $client = NTI\KeycloakClient\Admin\KeycloakClient::factory([
        ...
        'grant_type' => 'password',
        'username' => 'admin',
        'password' => '1234',
    ]);
  • client credentials
    • to authenticate with a client service account
    $client = NTI\KeycloakClient\Admin\KeycloakClient::factory([
        ...
        'grant_type' => 'client_credentials',
        'client_id' => 'admin-cli',
        'client_secret' => '84ab3d98-a0c3-44c7-b532-306f222ce1ff',
    ]);

Injecting middleware

It is possible to inject Guzzle client middleware in the keycloak client configuration using the middlewares keyword.

For example:

use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;

$client = NTI\KeycloakClient\Admin\KeycloakClient::factory([
    ...
    'middlewares' => [
        // throws exceptions when request fails
        Middleware::httpErrors(),
        // other custom middlewares
        Middleware::mapRequest(function (RequestInterface $request) {
            return $request;
        }),
    ],
]);

Changing how the token is saved and stored

By default, the token is saved at runtime. This means that the previous token is not used when creating a new client.

You can customize how the token is stored in the client configuration by implementing your own TokenStorage, an interface which describes how the token is stored and retrieved.

class CustomTokenStorage implements TokenStorage 
{
    public function getToken() 
    {
        // TODO
    }
    
    public function saveToken(array $token)
    {
        // TODO
    }
}

$client = NTI\KeycloakClient\Admin\KeycloakClient::factory([
    ...
    'token_storage' => new CustomTokenStorage(),
]);

Custom Keycloak endpoints

It is possible to inject Guzzle Service Operations in the keycloak client configuration using the custom_operations keyword. This way you can extend the built-in supported endpoints with custom.

$client = KeycloakClient::factory([
...
    'custom_operations' => [
        'getUsersByAttribute' => [
            'uri' => '/auth/realms/{realm}/userapi-rest/users/search-by-attr',
            'description' => 'Get users by attribute Returns a list of users, filtered according to query parameters',
            'httpMethod' => 'GET',
            'parameters' => [
                'realm' => [
                    'location' => 'uri',
                    'description' => 'The Realm name',
                    'type' => 'string',
                    'required' => true,
                ],
                'attr' => [
                    'location' => 'query',
                    'type' => 'string',
                    'required' => true,
                ],
                'value' => [
                    'location' => 'query',
                    'type' => 'string',
                    'required' => true,
                ],
            ],
        ],
    ]
]);

Supported APIs

Attack Detection

Authentication Management

Client Attribute Certificate

Client Initial Access

Client Registration Policy

Client Role Mappings

Client Scopes

Clients

Component

Groups

Identity Providers

Key

Protocol Mappers

Note: Ids are sent as clientScopeId or clientId and mapperId everything else is just as the keycloak documentation

Realms Admin

Role Mapper

Roles

Roles (by ID)

Scope Mappings

User Storage Provider

Users

Root