Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Oauth2 Keycloak Laravel Package

stevenmaguire/oauth2-keycloak

Laravel-friendly OAuth2 client provider for Keycloak using theleague/oauth2-client. Handles Keycloak authorization, token retrieval/refresh, and user profile fetching so your app can authenticate via Keycloak with minimal setup.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • OAuth2 Integration: The package (stevenmaguire/oauth2-keycloak) extends the league/oauth2-client library, making it a natural fit for Laravel applications requiring Keycloak-based authentication (e.g., SSO, role-based access, or federated identity).
  • Laravel Ecosystem Compatibility: Aligns with Laravel’s socialite or oauth packages (e.g., socialiteproviders/keycloak), but offers direct Keycloak-specific optimizations (e.g., token handling, realm-specific configurations).
  • Use Cases:
    • Enterprise SSO: Ideal for apps needing Keycloak integration (e.g., multi-tenant SaaS, internal tools).
    • Legacy System Modernization: Bridges older PHP/Laravel apps to Keycloak without rewriting auth logic.
    • Microservices: Enables secure service-to-service auth via OAuth2 flows (client credentials, PKCE).

Integration Feasibility

  • Laravel-Specific Hooks:
    • Works with Laravel’s authentication guards (e.g., keycloak guard in config/auth.php).
    • Supports Laravel Passport for token validation if combined with Keycloak’s OAuth2 endpoints.
  • Configuration Overhead:
    • Requires Keycloak client ID/secret, realm, and endpoint URLs (minimal setup if Keycloak is pre-configured).
    • Token Introspection: May need custom logic for Keycloak-specific claims (e.g., groups, roles).
  • Dependency Conflicts:
    • Risk of version mismatches with league/oauth2-client (check Laravel’s PHP version support).
    • Potential conflicts with other OAuth packages (e.g., laravel/socialite).

Technical Risk

  • Keycloak Version Lock:
    • Package may lag behind Keycloak’s latest features (e.g., dynamic client registration, new token formats).
    • Mitigation: Test with Keycloak’s LTS versions (e.g., 23.x) and monitor for deprecations.
  • Custom Claim Handling:
    • Keycloak’s groups or resource_access claims may require manual mapping to Laravel’s user model.
    • Risk: Incomplete claim parsing could lead to access control bugs.
  • PKCE Support:
    • Ensure the package supports PKCE (Proof Key for Code Exchange) for public clients (e.g., SPAs).
    • Fallback: Use league/oauth2-client directly if PKCE is critical.

Key Questions

  1. Keycloak Topology:
    • Is Keycloak self-hosted (on-prem/K8s) or managed (e.g., Red Hat SSO)? Affects endpoint URLs and token validation.
  2. Token Validation:
    • Will you use Keycloak’s introspection endpoint or validate tokens locally (e.g., with firebase/php-jwt)?
  3. User Sync:
    • How will user attributes (e.g., email, groups) map to Laravel’s users table?
  4. Fallback Strategy:
    • What’s the plan if Keycloak is down? (e.g., local auth fallback, graceful degradation).
  5. Performance:
    • Will token introspection be cached (e.g., Redis) to avoid Keycloak rate limits?

Integration Approach

Stack Fit

  • Laravel Core:
    • Replace or extend Laravel’s default auth with a custom guard using this package.
    • Example: Extend Illuminate\Auth\GuardHelpers for Keycloak-specific logic.
  • Service Layer:
    • Use Laravel’s service container to bind the OAuth2 client:
      $this->app->bind(\Stevenmaguire\OAuth2\ClientProvider::class, function ($app) {
          return new \Stevenmaguire\OAuth2\ClientProvider(
              config('services.keycloak.client_id'),
              config('services.keycloak.client_secret'),
              config('services.keycloak.realm'),
              config('services.keycloak.endpoint')
          );
      });
      
  • Middleware:
    • Create middleware to validate Keycloak tokens on protected routes:
      public function handle($request, Closure $next) {
          $token = $request->bearerToken();
          if (!$token || !auth()->guard('keycloak')->validateToken($token)) {
              return response()->json(['error' => 'Unauthorized'], 401);
          }
          return $next($request);
      }
      

Migration Path

  1. Phase 1: Proof of Concept (PoC)
    • Integrate the package in a non-production environment.
    • Test flows: Authorization Code, Client Credentials, and PKCE.
    • Validate token parsing and user attribute mapping.
  2. Phase 2: Laravel Guard Integration
    • Extend Laravel’s auth system with a KeycloakGuard:
      class KeycloakGuard extends Guard {
          public function validateToken($token) {
              return $this->provider->validateToken($token);
          }
      }
      
  3. Phase 3: Role/Group Sync
    • Sync Keycloak groups or roles to Laravel’s policies or gates.
    • Example: Use a model observer to update user roles on login.
  4. Phase 4: Monitoring & Optimization
    • Log token validation failures and Keycloak latency.
    • Implement circuit breakers (e.g., with spatie/fractal) for Keycloak downtime.

Compatibility

  • Laravel Versions:
    • Test with Laravel 10.x/11.x (PHP 8.1+). Older versions may need polyfills.
  • Keycloak Versions:
    • Target Keycloak 20+ for modern features (e.g., dynamic client registration).
    • Deprecation Risk: Keycloak’s OAuth2 endpoints may change (e.g., /protocol/openid-connect).
  • Database Schema:
    • Ensure the users table has fields for Keycloak-specific attributes (e.g., keycloak_sub, keycloak_groups).

Sequencing

  1. Pre-requisites:
    • Configure Keycloak with a client for your Laravel app (set Access Type, Valid Redirect URIs, etc.).
    • Install dependencies:
      composer require stevenmaguire/oauth2-keycloak league/oauth2-client
      
  2. Core Integration:
    • Publish config files (if any) and update config/services.php:
      'keycloak' => [
          'client_id' => env('KEYCLOAK_CLIENT_ID'),
          'client_secret' => env('KEYCLOAK_CLIENT_SECRET'),
          'realm' => env('KEYCLOAK_REALM'),
          'endpoint' => env('KEYCLOAK_ENDPOINT', 'https://keycloak.example.com/auth/realms/{realm}'),
      ],
      
  3. Authentication Flow:
    • Implement login redirects to Keycloak:
      use Stevenmaguire\OAuth2\ClientProvider;
      
      $provider = new ClientProvider($clientId, $clientSecret, $realm, $endpoint);
      $authUrl = $provider->getAuthorizationUrl(['scope' => 'openid profile email']);
      
  4. Post-Integration:
    • Test token exchange, refresh flows, and logout (Keycloak’s /logout endpoint).
    • Secure API routes with bearer tokens validated via the package.

Operational Impact

Maintenance

  • Dependency Updates:
    • Monitor stevenmaguire/oauth2-keycloak and league/oauth2-client for breaking changes.
    • Strategy: Pin versions in composer.json until stability is confirmed.
  • Keycloak Schema Changes:
    • Keycloak updates (e.g., new token claims) may require package or custom logic updates.
    • Mitigation: Subscribe to Keycloak’s release notes and test early.
  • Logging:
    • Log OAuth2 errors (e.g., invalid_grant, server_error) for debugging.
    • Example:
      try {
          $token = $provider->getAccessToken('authorization_code', ['code' => $code]);
      } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
          Log::error('Keycloak OAuth2 error: ' . $e->getMessage());
      }
      

Support

  • Troubleshooting:
    • Common Issues:
      • CORS: Ensure Keycloak’s web_origins include your Laravel app’s domain.
      • Token Expiry: Handle access_token refresh proactively.
      • Claim Mismatches: Validate Keycloak’s userinfo endpoint response structure.
    • Debugging Tools:
      • Use **Keycloak
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope