PHP code example of sistemas-eel / sso-client
1. Go to this page and download the library: Download sistemas-eel/sso-client 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/ */
sistemas-eel / sso-client example snippets
use SistemasEel\SSOClient\Laravel\Http\Controllers\SSOController;
use Illuminate\Support\Facades\Route;
Route::middleware('web')->group(function () {
Route::get('/login', [SSOController::class, 'login'])
->block(30, 30)
->name('login');
Route::get('/logout', [SSOController::class, 'logout'])
->name('logout');
});
// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ...
\SistemasEel\SSOClient\Laravel\Http\Middleware\CheckSSOSession::class,
],
];
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use SistemasEel\SSOClient\Laravel\Http\Middleware\CheckSSOSession;
->withMiddleware(function (Middleware $middleware): void {
$middleware->redirectGuestsTo(
fn (Request $request) => route('login', [
'intended' => $request->fullUrl(),
]),
);
$middleware->appendToGroup('web', [
CheckSSOSession::class,
]);
})
use Illuminate\Support\Facades\Auth;
if (Auth::check()) {
$user = Auth::user();
echo "Bem-vindo, {$user->name}";
}
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
}
Route::middleware(['auth', 'client_permission:user'])->group(function () {
Route::get('/dashboard', fn () => 'ok');
});
Route::middleware(['auth', 'client_permission:admin'])->prefix('admin')->group(function () {
Route::get('/', fn () => 'admin');
});
use SistemasEel\SSOClient\Laravel\Support\ClientPermission;
if (ClientPermission::has('admin')) {
// ...
}
// sso/config.php
return [
'server_url' => 'https://portalsistemas.unidade.usp.br/portal-sistemas',
'client_id' => 'seu_client_id',
'client_secret' => 'seu_client_secret',
'redirect_uri' => 'https://seu-sistema.com.br/sso/callback.php',
'verify_ssl' => true,
'ca_bundle' => null,
'webhook_secret' => 'seu_webhook_secret',
'home_path' => '/dashboard.php',
'login_url' => '/sso/login.php',
'logout_url' => '/sso/logout.php',
'logout_redirect' => '/index.php',
'cache_dir' => __DIR__ . '/cache',
'session_prefix' => 'sso_',
];
// sso/bootstrap.php
use SistemasEel\SSOClient\Cache\FileCacheHandler;
use SistemasEel\SSOClient\Core\SSOClient;
use SistemasEel\SSOClient\Session\SessionHandler;
$config = _bundle']
);
$session = new SessionHandler($config['session_prefix']);
$cache = new FileCacheHandler($config['cache_dir']);
// sso/login.php
m_bytes(20));
$session->set('oauth_state', $state);
header('Location: ' . $client->getAuthorizationUrl($state));
exit;
// sso/callback.php
$session->remove('oauth_state');
if (!$state || $_GET['state'] !== $state) {
die('OAuth state inválido');
}
// Troca código por token
$token = $client->exchangeCodeForToken($_GET['code']);
if (!$token || !isset($token['access_token'])) {
die('Falha ao obter token');
}
// Obtém usuário
$user = $client->getUserInfo($token['access_token']);
if (!$user || !isset($user['codpes'])) {
die('Falha ao obter dados do usuário');
}
# INTEGRAÇÃO COM O BANCO DE DADOS
# $pdo->prepare("SELECT * FROM users WHERE codpes = ?");
// Armazena sessão
$session->set('user_authenticated', true);
$session->set('user_codpes', $user['codpes']);
$session->set('user_name', $user['name'] ?? '');
$session->set('user_email', $user['email'] ?? '');
$session->set('access_token', $token['access_token']);
$session->set('refresh_token', $token['refresh_token'] ?? null);
$session->set('expires_at', time() + ($token['expires_in'] ?? 3600));
$session->set('login_timestamp', time());
$session->regenerate();
header('Location: ' . $config['home_path']);
exit;
// sso/session-check.php
nticated') || !$session->get('user_authenticated')) {
header('Location: ' . $config['login_url']);
exit;
}
// Exemplo simples de logout global
$globalLogout = $cache->get('sso_global_logout_' . $session->get('user_codpes'));
if ($globalLogout && $session->get('login_timestamp') && $globalLogout >= $session->get('login_timestamp')) {
$session->clear();
$session->destroy();
header('Location: ' . $config['logout_redirect'] . '?reason=global_logout');
exit;
}
$userCodpes = $session->get('user_codpes');
$userName = $session->get('user_name');
echo "Bem-vindo, {$userName}";
use SistemasEel\SSOClient\Core\SSOClient;
$client = new SSOClient(
$baseUrl, // URL do servidor SSO
$clientId, // Client ID
$clientSecret, // Client Secret
$redirectUri, // URI de redirecionamento
$verifySsl = true, // Verificação SSL (padrão: true)
$caBundle = null // Caminho para CA bundle (opcional)
);
$expected = hash_hmac('sha256', $timestamp . $nonce . $rawBody, $webhookSecret);
hash_equals($expected, $signature);
use SistemasEel\SSOClient\Session\SessionHandler;
$session = new SessionHandler('sso_');
$session->set('key', 'value'); // Armazena
$value = $session->get('key'); // Obtém
$oldValue = $session->remove('key');// Remove e retorna
$exists = $session->has('key'); // Verifica
$session->clear(); // Limpa variáveis SSO
$session->destroy(); // Destrói sessão
$session->regenerate(); // Regenera ID
use SistemasEel\SSOClient\Cache\FileCacheHandler;
$cache = new FileCacheHandler('/path/to/cache/dir');
$cache->put('key', 'value', 3600); // Armazena (1h TTL)
$value = $cache->get('key'); // Obtém
$cache->forget('key'); // Remove
bash
php artisan vendor:publish --tag=sso-client-config
bash
php artisan optimize:clear
bash
composer vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate