drago-ex / keycloak
Simple Keycloak adapter for easy integration.
v1.0.6
2025-01-27 07:14 UTC
Requires
- php: >=8.3 <9
- nette/application: ^3.1
- nette/di: ^3.0
- nette/http: ^3.1
- stevenmaguire/oauth2-keycloak: ^4.0.0
Requires (Dev)
- nette/bootstrap: ^3.0
- nette/tester: ^2.3
- phpstan/phpstan-nette: ^1.2.9
- tracy/tracy: ^2.10
This package is auto-updated.
Last update: 2025-03-27 13:01:58 UTC
README
Simple Keycloak adapter for easy integration.
Technology
- PHP 8.3 or higher
- composer
Installation
composer require drago-ex/keycloak
Extension registration in config.neon
extensions: keycloak: Drago\Keycloak\DI\KeycloakExtension keycloak: # https://github.com/stevenmaguire/oauth2-keycloak authServerUrl: keycloak-server-url realm: keycloak-realm clientId: keycloak-client-id clientSecret: keycloak-client-secret redirectUri: https://example.com/callback-url # optional # version: 21.0.1 # encryptionAlgorithm: 'RS256' # encryptionKeyPath: '../key.pem' # encryptionKey: 'contents_of_key_or_certificate' # https://github.com/guzzle/guzzle # guzzleHttp:
Usage in Presenter
use Drago\Keycloak\KeycloakAdapter; public function __construct( private Keycloak $keycloak, private KeycloakSessions $keycloakSessions, ) { parent::__construct(); } // Simple login protected function startup(): void { parent::startup(); if (!$this->getUser()->isLoggedIn()) { $keycloakUser = $this->keycloakSessions->getItems()->resourceOwner; $this->getUser()->login($keycloakUser->getName(), $keycloakUser->getId()); $this->redirect('redirect'); } } // Custom authentication with Keycloak attributes and backlink protected function startup(): void { parent::startup(); if (!$this->getUser()->isLoggedIn()) { $keycloakUser = $this->keycloakSessions->getItems()->resourceOwner; try { if ($keycloakUser) { $user = $this->getUser(); // Custom authenticator $user->setAuthenticator($this->authRepository); // User login $user->login($keycloakUser->getName(), $keycloakUser->getId()); // Backlink handling $this->restoreRequest($this->backlink); $this->redirect(':Backend:Admin:'); } } catch (AuthenticationException $e) { if ($e->getCode() === 1) { $this->template->userLoginError = true; $this->getUserLogout(); $redirect = $this->keycloak->getLogoutUrl(); header('refresh:6; url=' . $redirect); } } } } // User logout private function getUserLogout(): void { $this->getUser()->logout(); $this->keycloakSessions->remove(); }
Error message in @layout.latte
<body n:ifset="$userLoginError"> <h1 class="text-danger text-center mt-5"> {_'The user does not have the required attributes set in keycloak.'} </h1> </body> <body n:if="$user->loggedIn"> ... </body>
Items from Keycloak
// Get state, accessToken, and resource owner $this->keycloakSessions->getItems();
User Logout Method
$this->keycloakSessions->remove(); $this->redirectUrl($this->keycloak->getLogoutUrl());