Weave 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

Relay Keycloak Bundle Laravel Package

dbp/relay-keycloak-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Laravel project via Composer:

    composer require dbp/relay-keycloak-bundle
    

    Register the bundle in config/app.php under providers:

    DBP\Relay\KeycloakBundle\KeycloakServiceProvider::class,
    
  2. Configuration Publish the default config file:

    php artisan vendor:publish --provider="DBP\Relay\KeycloakBundle\KeycloakServiceProvider" --tag="config"
    

    Update .env with Keycloak server details:

    KEYCLOAK_REALM=your-realm
    KEYCLOAK_CLIENT_ID=your-client-id
    KEYCLOAK_CLIENT_SECRET=your-client-secret
    KEYCLOAK_BASE_URL=https://your-keycloak-server/auth
    
  3. First Use Case: Authentication Use the facade to authenticate a user:

    use DBP\Relay\KeycloakBundle\Facades\Keycloak;
    
    $token = Keycloak::authenticate([
        'username' => '[email protected]',
        'password' => 'password123',
        'grant_type' => 'password'
    ]);
    

Implementation Patterns

Workflows

  1. User Management

    • Create User:
      $user = Keycloak::createUser([
          'username' => 'newuser',
          'email' => '[email protected]',
          'enabled' => true,
          'credentials' => [
              ['type' => 'password', 'value' => 'securepass', 'temporary' => false]
          ]
      ]);
      
    • Update User:
      Keycloak::updateUser($userId, ['email' => '[email protected]']);
      
  2. Token Handling

    • Refresh Token:
      $refreshedToken = Keycloak::refreshToken($refreshToken);
      
    • Introspect Token (validate token):
      $isValid = Keycloak::introspectToken($token);
      
  3. Role Management

    • Assign role to user:
      Keycloak::assignRole($userId, 'admin');
      
    • Get user roles:
      $roles = Keycloak::getUserRoles($userId);
      

Integration Tips

  • Middleware for Protected Routes Create middleware to validate Keycloak tokens:

    namespace App\Http\Middleware;
    
    use Closure;
    use DBP\Relay\KeycloakBundle\Facades\Keycloak;
    
    class ValidateKeycloakToken
    {
        public function handle($request, Closure $next)
        {
            $token = $request->bearerToken();
            if (!$token || !Keycloak::introspectToken($token)) {
                abort(401, 'Unauthorized');
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'keycloak.auth' => \App\Http\Middleware\ValidateKeycloakToken::class,
    ];
    
  • Laravel Auth Integration Extend Laravel’s Authenticatable to use Keycloak tokens:

    use DBP\Relay\KeycloakBundle\Facades\Keycloak;
    
    class KeycloakUserProvider implements Authenticatable
    {
        public function retrieveByToken($token)
        {
            $user = Keycloak::introspectToken($token);
            return $user ? new User($user) : null;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry Handling

    • Keycloak tokens expire (default: 5 minutes for access tokens, 30 days for refresh tokens). Always handle 401 Unauthorized responses gracefully and refresh tokens when needed.
    • Tip: Store refresh tokens securely (e.g., encrypted in the database) and implement a token refresh mechanism in your middleware.
  2. Role Mapping

    • Keycloak roles are realm-specific. Ensure your Laravel roles map correctly to Keycloak roles to avoid permission issues.
    • Tip: Use a config file to define role mappings:
      'role_mappings' => [
          'admin' => 'Keycloak-Admin-Role',
          'user' => 'Keycloak-User-Role',
      ],
      
  3. Error Handling

    • Keycloak API returns HTTP errors (e.g., 400 Bad Request for invalid credentials). Wrap API calls in try-catch blocks:
      try {
          $token = Keycloak::authenticate($credentials);
      } catch (\DBP\Relay\KeycloakBundle\Exceptions\KeycloakException $e) {
          Log::error('Keycloak auth failed: ' . $e->getMessage());
          abort(401);
      }
      
  4. Rate Limiting

    • Keycloak may throttle requests. Implement exponential backoff for retries:
      use DBP\Relay\KeycloakBundle\KeycloakManager;
      
      $manager = app(KeycloakManager::class);
      $manager->setRetryPolicy(new \GuzzleHttp\RetryMiddleware([
          'max_retries' => 3,
          'delay' => 100,
          'multiplier' => 2,
      ]));
      

Debugging Tips

  1. Enable API Logging Configure Guzzle HTTP client logging in config/keycloak.php:

    'http_client' => [
        'debug' => env('KEYCLOAK_DEBUG', false),
    ],
    

    Check logs in storage/logs/laravel.log for API request/response details.

  2. Test with Postman Use Postman to manually test Keycloak endpoints (e.g., /auth/realms/{realm}/protocol/openid-connect/token) before integrating into Laravel.

  3. Validate Config Ensure .env values match your Keycloak server:

    • KEYCLOAK_BASE_URL must include /auth (e.g., https://keycloak.example.com/auth).
    • KEYCLOAK_REALM must exist in Keycloak.

Extension Points

  1. Custom Claims Extend the User model to include Keycloak claims:

    class User extends Authenticatable
    {
        public function getKeycloakClaims()
        {
            return Keycloak::getUserInfo($this->keycloak_id)['userinfo'];
        }
    }
    
  2. Webhook Events Listen to Keycloak events (e.g., user creation) via Keycloak’s admin REST API:

    Keycloak::listenForEvent('create', function ($user) {
        // Trigger Laravel event or queue job
        event(new UserRegistered($user));
    });
    
  3. Custom Adapters Override the default HTTP adapter for custom logic (e.g., proxy support):

    $manager = app(KeycloakManager::class);
    $manager->setHttpClient(new \GuzzleHttp\Client([
        'base_uri' => env('KEYCLOAK_BASE_URL'),
        'proxy' => env('HTTP_PROXY'),
    ]));
    
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings