PHP code example of mainick / keycloak-client-bundle

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

    

mainick / keycloak-client-bundle example snippets


// config/bundles.php

return [
    // ...
    Mainick\KeycloakClientBundle\MainickKeycloakClientBundle::class => ['all' => true],
];



declare(strict_types=1);

namespace App\Service;

use Mainick\KeycloakClientBundle\Interface\IamClientInterface;

class IamService
{
    public function __construct(
        private IamClientInterface $iamClient
    ) {
    }
}

// authenticate the user with username and password
$accessToken = $this->iamClient->authenticate($username, $password);

// authenticate the user with authorization code
$accessToken = $this->iamClient->authenticateCodeGrant($authorizationCode);

// verify and introspect the token
$userRepresentation = $this->iamClient->verifyToken($accessToken);
echo $userRepresentation->id; // id
echo $userRepresentation->username; // username
echo $userRepresentation->email; // email
echo $userRepresentation->firstName; // first name
echo $userRepresentation->lastName; // last name
echo $userRepresentation->name; // full name
echo $userRepresentation->groups; // all groups assigned to the user
echo $userRepresentation->realmRoles; // realm roles assigned to the user
echo $userRepresentation->clientRoles; // client roles assigned to the user
echo $userRepresentation->applicationRoles; // specific client roles assigned to the user
echo $userRepresentation->attributes; // additional user attributes

// refresh the token
$accessToken = $this->iamClient->refreshToken($accessToken);

// get user info
$userInfo = $this->iamClient->userInfo($accessToken);
echo $userInfo->id; // id
echo $userInfo->username; // username
echo $userInfo->email; // email
echo $userInfo->firstName; // first name
echo $userInfo->lastName; // last name
echo $userInfo->name; // full name
echo $userInfo->groups; // all groups assigned to the user
echo $userInfo->realmRoles; // realm roles assigned to the user
echo $userInfo->clientRoles; // client roles assigned to the user
echo $userInfo->applicationRoles; // specific client roles assigned to the user
echo $userInfo->attributes; // additional user attributes

// has role
$hasRole = $this->iamClient->hasRole($accessToken, $roleName);

// has any role
$hasAnyRole = $this->iamClient->hasAnyRole($accessToken, $roleNames);

// has all roles
$hasAllRoles = $this->iamClient->hasAllRoles($accessToken, $roleNames);

// has group
$hasGroup = $this->iamClient->hasGroup($accessToken, $groupName);

// has any group
$hasAnyGroup = $this->iamClient->hasAnyGroup($accessToken, $groupNames);

// has all groups
$hasAllGroups = $this->iamClient->hasAllGroups($accessToken, $groupNames);

// has scope
$hasScope = $this->iamClient->hasScope($accessToken, $scopeName);

// has any scope
$hasAnyScope = $this->iamClient->hasAnyScope($accessToken, $scopeNames);

// has all scopes
$hasAllScopes = $this->iamClient->hasAllScopes($accessToken, $scopeNames);

// get the user object from the request
$user = $request->attributes->get('user');

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Mainick\KeycloakClientBundle\Annotation\ExcludeTokenValidationAttribute;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    #[Route("/path/to/excluded/route", name: "app.excluded_route", methods: ["GET"])]
    #[ExcludeTokenValidationAttribute]
    public function excludedRouteAction(): Response
    {
        // This route is excluded from token validation.
        // ...
    }
}

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use Mainick\KeycloakClientBundle\Annotation\ExcludeTokenValidationAttribute;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    #[Route("/logout", name: "app.logout", methods: ["GET"])]
    public function logout(): RedirectResponse
    {
        return $this->redirectToRoute('mainick_keycloak_security_auth_logout');
    }
}



declare(strict_types=1);

namespace App\Service;

use Mainick\KeycloakClientBundle\Interface\IamAdminClientInterface;

class IamAdminService
{
    public function __construct(
        private IamAdminClientInterface $iamAdminClient
    ) {
    }
}

// List all realms: RealmCollection of the RealmRepresentation
$realms = $iamAdminClient->realms()->all();

// List all clients: ClientCollection of the ClientRepresentation
$clients = $iamAdminClient->clients()->all(realm: 'realm-test');

// List all users: UserCollection of the UserRepresentation
$users = $iamAdminClient->users()->all(realm: 'realm-test');

// List all groups: GroupCollection of the GroupRepresentation
$groups = $iamAdminClient->groups()->all(realm: 'realm-test');

// List all roles: RoleCollection of the RoleRepresentation
$roles = $iamAdminClient->roles()->all(realm: 'realm-test');

// Get a realm by name
$realmRepresentation = $iamAdminClient->realms()->get(realm: 'realm-test');

// Get a client by UUID
$clientRepresentation = $iamAdminClient->clients()->get(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd'
);

// Get a user by ID
$userRepresentation = $iamAdminClient->users()->get(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

// Get a group by ID
$groupRepresentation = $iamAdminClient->groups()->get(
    realm: 'realm-test',
    groupId: '190990fa-cdbf-4b31-b561-0cfc03737414'
);

// Get a realm role by name
$roleRealmRepresentation = $iamAdminClient->roles()->get(
    realm: 'realm-test',
    roleName: 'ROLE_USER_VIEW'
);

// Get a client role by name
$roleClientRepresentation = $iamAdminClient->clients()->role(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    roleName: 'ROLE_ADD_AGENT'
);

// Create a new realm
$realmRepresentation = new RealmRepresentation(
    realm: 'realm-test',
    displayName: 'Test Realm',
    enabled: true,
);
$realmCreated = $iamAdminClient->realms()->create($realmRepresentation);

// Create a new client (specify the realm)
$clientRepresentation = new ClientRepresentation(
    name: 'client-test',
    enabled: true,
);
$clientCreated = $iamAdminClient->clients()->create(
    realm: 'realm-test',
    client: $clientRepresentation
);

// Update a realm
$realmRepresentation = $iamAdminClient->realms()->get(realm: 'realm-test');
$realmRepresentation->displayName = 'New display name';
$realmUpdated = $iamAdminClient->realms()->update($realm, $realmRepresentation);

// Update a client (specify the realm)
$clientRepresentation = $iamAdminClient->clients()->get(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd'
);
$clientRepresentation->description = 'Client test updated';
$clientUpdated = $iamAdminClient->clients()->update(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    clientRepresentation: $clientRepresentation
);

// Delete a realm
$realmDeleted = $iamAdminClient->realms()->delete(realm: 'realm-test');

// Delete a client (specify the realm)
$clientDeleted = $iamAdminClient->clients()->delete(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd'
);

// List all sessions: UserSessionCollection of the UserSessionRepresentation
$sessions = $iamAdminClient->users()->sessions(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

// List all groups: GroupCollection of the GroupRepresentation
$groups = $iamAdminClient->users()->groups(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

$groups = $iamAdminClient->users()->joinGroup(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3',
    groupId: '190990fa-cdbf-4b31-b561-0cfc03737414'
);

$groups = $iamAdminClient->users()->leaveGroup(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3',
    groupId: '190990fa-cdbf-4b31-b561-0cfc03737414'
);

// List all realm roles: RoleCollection of the RoleRepresentation
$userRolesRealm = $iamAdminClient->users()->realmRoles(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

// List all client roles: RoleCollection of the RoleRepresentation
$userRolesClient = $iamAdminClient->users()->clientRoles(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

// List all available realm roles: RoleCollection of the RoleRepresentation
$userRolesRealm = $iamAdminClient->users()->availableRealmRoles(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

// List all available client roles: RoleCollection of the RoleRepresentation
$userRolesClient = $iamAdminClient->users()->availableClientRoles(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);

// Assign a realm role to a user
$roleRealmRepresentation = $iamAdminClient->roles()->get(
    realm: 'realm-test',
    roleName: 'ROLE_REALM_TEST',
);
$iamAdminClient->users()->addRealmRole(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3',
    role: $roleRealmRepresentation
);

// Assign a client role to a user
$roleClientRepresentation = $iamAdminClient->clients()->role(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    roleName: 'ROLE_CLIENT_TEST',
);
$iamAdminClient->users()->addClientRole(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3',
    role: $roleClientRepresentation
);

// Remove a realm role from a user
$roleRealmRepresentation = $iamAdminClient->roles()->get(
    realm: 'realm-test',
    roleName: 'ROLE_REALM_TEST',
);
$iamAdminClient->users()->removeRealmRole(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3',
    role: $roleRealmRepresentation
);

// Remove a client role from a user
$roleClientRepresentation = $iamAdminClient->clients()->role(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    roleName: 'ROLE_CLIENT_TEST',
);
$iamAdminClient->users()->removeClientRole(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3',
    role: $roleClientRepresentation
);

/** @var GroupCollection $groups */
$groups = $iamAdminClient->groups()->all(realm: 'realm-test');
if ($groups->count()) {
    $level = 1;
    foreach ($groups as $group) {
        echo sprintf('%s> Group "%s"'."<br/>", str_repeat('-', $level), $group->name);

        if ($group->subGroupCount) {
            /** @var GroupCollection $subGroups */
            $subGroups = $iamAdminClient->groups()->children(
                realm: 'realm-test',
                groupId: $group->id
            );
            if ($subGroups->count()) {
                $level++;
                foreach ($subGroups as $subGroup) {
                    echo sprintf('%s> SubGroup "%s"'."<br/>", str_repeat('-', $level), $subGroup->name);
                }
            }
        }
    }
}

$subGroupRepresentation = new GroupRepresentation(
    name: 'Test Sub Group',
);
$groups = $iamAdminClient->groups()->createChild(
    realm: 'realm-test',
    parentGroupId: '190990fa-cdbf-4b31-b561-0cfc03737414',
    group: $subGroupRepresentation
);

// List all users: UserCollection of the UserRepresentation
$users = $iamAdminClient->groups()->users(
    realm: 'realm-test',
    groupId: '190990fa-cdbf-4b31-b561-0cfc03737414'
);

// List all realm roles: RoleCollection of the RoleRepresentation
$rolesRealm = $iamAdminClient->roles()->all(realm: 'realm-test');

// List all client roles: RoleCollection of the RoleRepresentation
$rolesClient = $iamAdminClient->clients()->roles(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd'
);

// Create a new realm role
$roleRepresentation = new RoleRepresentation(
    name: 'ROLE_REALM_TEST',
    description: 'Role Realm for test',
);
$roleRealm = $iamAdminClient->roles()->create(
    realm: 'realm-test',
    role: $roleRepresentation
);

// Create a new client role
$roleRepresentation = new RoleRepresentation(
    name: 'ROLE_CLIENT_TEST',
    description: 'Role Client for test',
);
$roleClient = $iamAdminClient->clients()->createRole(
    realm: $realm,
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    role: $roleRepresentation
);

// Update a realm role
$roleRealmRepresentation = $iamAdminClient->roles()->get(
    realm: 'realm-test',
    roleName: 'ROLE_REALM_TEST',
);
$roleRealmRepresentation->description = 'Description test';
$roleRealmUpdated = $iamAdminClient->roles()->update(
    realm: 'realm-test',
    roleName: 'ROLE_REALM_TEST',
    roleRepresentation: $roleRealmRepresentation,
);

// Update a client role
$roleClientRepresentation = $iamAdminClient->clients()->role(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    roleName: 'ROLE_CLIENT_TEST',
);
$roleClientRepresentation->description = 'Description test';
$roleClientUpdated = $iamAdminClient->clients()->updateRole(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    roleName: 'ROLE_CLIENT_TEST',
    roleRepresentation: $roleClientRepresentation,
);

// Delete a realm role
$roleRealmDeleted = $iamAdminClient->roles()->delete(
    realm: 'realm-test',
    roleName: 'ROLE_REALM_TEST',
);

// Delete a client role
$roleClientDeleted = $iamAdminClient->clients()->deleteRole(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd',
    roleName: 'ROLE_CLIENT_TEST'
);

$userProfileConfig = $iamAdminClient->users()->getProfileConfig($realm);

if ($userProfileConfig->unmanagedAttributePolicy === UnmanagedAttributePolicyEnum::ADMIN_EDIT) {
    echo "Unmanaged attribute policy is set to ADMIN_EDIT. You can edit unmanaged attributes.";
}

$user = $iamAdminClient->users()->get(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);
$user->attributes = $user->attributes->with('school', ['school1', 'school2']);

$userUpdated = $iamAdminClient->users()->update(
    realm: 'realm-test',
    userId: $user->id,
    user: $user);

$user = $iamAdminClient->users()->get(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);
$user->attributes = $user->attributes->with('social', ['mainick-facebook']);

$userUpdated = $iamAdminClient->users()->update(
    realm: 'realm-test',
    userId: $user->id,
    user: $user
);

$user = $iamAdminClient->users()->get(
    realm: 'realm-test',
    userId: '8cd92f79-7919-4486-a0fb-0cb7dd517ac3'
);
$user->attributes = $user->attributes->without('social');

$userUpdated = $iamAdminClient->users()->update(
    realm: 'realm-test',
    userId: $user->id,
    user: $user
);

$userSessions = $iamAdminClient->clients()->getUserSessions(
    realm: 'realm-test',
    clientUuid: '32f77927-0bfd-4ef2-8e27-2932984634cd'
);
if ($userSessions->count()) {
    echo sprintf('Client %s has %d user sessions %s', $client->clientId, $userSessions->count(), PHP_EOL);
}