PHP code example of marchenkovma / laravel-keycloak
1. Go to this page and download the library: Download marchenkovma/laravel-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/ */
// config/keycloak.php
'fallback_role' => env('KEYCLOAK_FALLBACK_ROLE'), // например demo
use Marchenkovma\LaravelKeycloak\Facades\Keycloak;
Keycloak::role(); // 'admin' | 'user' | null
Keycloak::hasRole('admin'); // true, если роль одна из перечисленных
// Gate проект определяет сам
Gate::define('admin', fn ($user) => Keycloak::hasRole('admin'));
Route::middleware(['auth', 'keycloak.role'])->group(...); // любая роль приложения
Route::middleware(['auth', 'keycloak.role:admin'])->group(...); // только admin
'redirects' => [
'after_login' => 'home', // имя маршрута; redirect()->intended() поверх
'after_logout' => 'home',
'on_failure' => null, // устаревший state при входе; null: на after_logout
],
// routes/web.php
use App\Http\Controllers\Auth\WelcomeController;
Route::get('welcome', WelcomeController::class)->middleware('guest')->name('welcome');
// только Keycloak
Route::middleware('auth:keycloak')->group(...);
// Keycloak или Sanctum: кто узнал токен, тот и пустил
Route::middleware('auth:keycloak,sanctum')->group(...);
$client = $request->user();
$client->getAuthIdentifier(); // azp, например 'reports-api'
$client->claims; // все claims токена
$client->hasRole('orders-api', 'read'); // роль из resource_access
$client->hasScope('email');
Keycloak::resolveApiClientUsing(fn (array $claims) => new ApiClient(['name' => $claims['azp']]));
use Marchenkovma\LaravelKeycloak\Facades\Keycloak;
Http::withToken(Keycloak::serviceToken())->get('https://orders.example.com/api/v1/orders');
use Marchenkovma\LaravelKeycloak\Testing\InteractsWithKeycloak;
abstract class TestCase extends BaseTestCase
{
use InteractsWithKeycloak;
}
// API: настоящий RS256-токен, guard проверяет его полностью, без Keycloak
$this->withKeycloakToken()->getJson('/api/v1/orders')->assertOk();
$this->withKeycloakToken(['resource_access' => null])->getJson('/api/v1/orders')->assertUnauthorized();
$this->withKeycloakToken(['resource_access' => ['orders-api' => ['roles' => ['other']]]])
->getJson('/api/v1/orders')->assertUnauthorized();
// Вход пользователя с ролью в сессии, без Socialite
$this->actingAsKeycloakUser($user, 'admin')->get('/')->assertOk();