PHP code example of drago-ex / keycloak

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

    

drago-ex / keycloak example snippets


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();
}


// Get state, accessToken, and resource owner
$this->keycloakSessions->getItems();

$this->keycloakSessions->remove();
$this->redirectUrl($this->keycloak->getLogoutUrl());