fschmtt/keycloak-rest-api-client-php

PHP客户端,用于与Keycloak的Admin REST API交互。


README

codecov PHP Analysis PHP Unit PHP Integration (Keycloak compatibility) PHP Legacy (Keycloak compatibility)

Keycloak Admin REST API客户端

PHP客户端,用于与Keycloak的Admin REST API交互。

灵感来源于keycloak/keycloak-nodejs-admin-client

安装

通过Composer安装

composer require fschmtt/keycloak-rest-api-client-php

使用方法

示例

$keycloak = new \Fschmtt\Keycloak\Keycloak(
    baseUrl: 'http://keycloak:8080',
    username: 'admin',
    password: 'admin'
);

$serverInfo = $keycloak->serverInfo()->get();

echo sprintf(
    'Keycloak %s is running on %s/%s (%s) with %s/%s since %s and is currently using %s of %s (%s %%) memory.',
    $serverInfo->getSystemInfo()->getVersion(),
    $serverInfo->getSystemInfo()->getOsName(),
    $serverInfo->getSystemInfo()->getOsVersion(),
    $serverInfo->getSystemInfo()->getOsArchitecture(),
    $serverInfo->getSystemInfo()->getJavaVm(),
    $serverInfo->getSystemInfo()->getJavaVersion(),
    $serverInfo->getSystemInfo()->getUptime(),
    $serverInfo->getMemoryInfo()->getUsedFormated(),
    $serverInfo->getMemoryInfo()->getTotalFormated(),
    100 - $serverInfo->getMemoryInfo()->getFreePercentage(),
);

将打印,例如。

Keycloak 25.0.0 is running on Linux/5.10.25-linuxkit (amd64) with OpenJDK 64-Bit Server VM/11.0.11 since 0 days, 2 hours, 37 minutes, 7 seconds and is currently using 139 MB of 512 MB (28 %) memory.

更多示例可以在示例目录中找到。

自定义

自定义表示和资源

您可以通过提供自己的表示和资源来注册和使用自定义资源,例如。

class MyCustomRepresentation extends \Fschmtt\Keycloak\Representation\Representation
{
    public function __construct(
        protected ?string $id = null,
        protected ?string $name = null,
    ) {
    }
}

class MyCustomResource extends \Fschmtt\Keycloak\Resource\Resource
{
    public function myCustomEndpoint(): MyCustomRepresentation
    {
        return $this->queryExecutor->executeQuery(
            new \Fschmtt\Keycloak\Http\Query(
                '/my-custom-endpoint',
                MyCustomRepresentation::class,
            )
        );
    }
}

通过扩展Resource类,您可以访问QueryExecutorCommandExecutorCommandExecutor旨在在服务器上运行状态更改命令(不返回响应);QueryExecutor允许从服务器获取资源和表示。

要使用您的自定义资源,将完全限定类名(FQCN)传递给Keycloak::resource()方法。它为您提供一个实例,您可以然后使用它

$keycloak = new Keycloak(
    $_SERVER['KEYCLOAK_BASE_URL'] ?? 'http://keycloak:8080',
    'admin',
    'admin',
);

$myCustomResource = $keycloak->resource(MyCustomResource::class);
$myCustomRepresentation = $myCustomResource->myCustomEndpoint();

可用资源

攻击检测

客户端

域管理员

用户

角色

本地开发和测试

运行docker compose up -d keycloak以启动一个监听于https://:8080的本地Keycloak实例。

php容器中运行您的脚本(例如,examples/serverinfo.php

docker compose run --rm php php examples/serverinfo.php

Composer脚本

  • analyze:运行phpstan分析
  • ecs:运行Easy Coding Standard (ECS)
  • ecs:fix:修复Easy Coding Standard (ECS)错误
  • test:运行单元和集成测试
  • test:unit:运行单元测试
  • test:integration:运行集成测试(需要一个新的且正在运行的Keycloak实例)