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

Openid Bundle Laravel Package

dontdrinkandroot/openid-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dontdrinkandroot/openid-bundle
    

    Add to config/app.php under providers:

    Dontdrinkandroot\OpenidBundle\OpenidBundle::class,
    
  2. Publish Configuration

    php artisan vendor:publish --provider="Dontdrinkandroot\OpenidBundle\OpenidBundle" --tag="config"
    

    Edit config/openid.php to configure your OpenID provider (e.g., Google, GitHub, or custom).

  3. First Use Case: Login via OpenID Add a route in routes/web.php:

    Route::get('/login/openid', [OpenidController::class, 'login'])->name('openid.login');
    Route::get('/openid/callback', [OpenidController::class, 'callback'])->name('openid.callback');
    

    Use the OpenidController to handle authentication:

    use Dontdrinkandroot\OpenidBundle\Controller\OpenidController;
    

Implementation Patterns

Workflows

  1. Authentication Flow

    • Redirect users to /login/openid to initiate OpenID login.
    • The bundle handles the OAuth2 flow, returning a callback to /openid/callback.
    • Use middleware to protect routes:
      Route::middleware(['auth:openid'])->group(function () {
          // Protected routes
      });
      
  2. User Integration

    • After successful authentication, the bundle fires an OpenidAuthenticated event. Listen to it in an event service provider:
      public function boot()
      {
          event(new OpenidAuthenticated($user));
      }
      
    • Sync user data with your Laravel models (e.g., User):
      $user = User::firstOrCreate([
          'openid_provider' => $provider,
          'openid_id' => $openidId,
      ], [
          'name' => $userData['name'],
          'email' => $userData['email'],
      ]);
      
  3. Custom Providers

    • Extend the OpenidProvider class to support non-standard providers:
      namespace App\Openid;
      
      use Dontdrinkandroot\OpenidBundle\OpenidProvider;
      
      class CustomProvider extends OpenidProvider
      {
          public function getAuthUrl(): string
          {
              return 'https://custom-provider.com/oauth/authorize';
          }
      
          public function getTokenUrl(): string
          {
              return 'https://custom-provider.com/oauth/token';
          }
      }
      
    • Register the provider in config/openid.php:
      'providers' => [
          'custom' => [
              'class' => App\Openid\CustomProvider::class,
              'client_id' => env('CUSTOM_CLIENT_ID'),
              'client_secret' => env('CUSTOM_CLIENT_SECRET'),
          ],
      ],
      
  4. Session Management

    • Use the OpenidGuard to manage sessions:
      Auth::guard('openid')->attempt($credentials);
      

Gotchas and Tips

Pitfalls

  1. Missing Configuration

    • Forgetting to publish the config (php artisan vendor:publish) will result in undefined provider settings. Always verify config/openid.php after installation.
  2. Callback URL Mismatch

    • Ensure the redirect_uri in your OpenID provider settings matches the callback route (/openid/callback). Mismatches will cause authentication failures.
  3. State Parameter Handling

    • The bundle uses the state parameter for CSRF protection. If you modify the flow (e.g., adding custom query params), ensure the state is preserved and validated.
  4. User Data Mapping

    • The bundle does not automatically map OpenID user data to your Laravel models. You must handle this in the OpenidAuthenticated event listener or override the handleAuthentication method in a custom provider.
  5. Token Expiry

    • Refresh tokens may expire. Implement a fallback mechanism (e.g., re-authentication) or use the provider’s token refresh endpoint if supported.

Debugging

  • Enable Logging Add to config/logging.php to debug OpenID requests:

    'channels' => [
        'openid' => [
            'driver' => 'single',
            'path' => storage_path('logs/openid.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log requests in your custom provider:

    \Log::channel('openid')->debug('Auth URL:', [$this->getAuthUrl()]);
    
  • Check Provider Responses Use dd() or Log::debug() to inspect the raw response from the OpenID provider:

    $response = $this->getAuthResponse();
    \Log::debug('Provider Response:', [$response->getBody()]);
    

Tips

  1. Environment Variables Store sensitive data (e.g., client_id, client_secret) in .env:

    OPENID_GOOGLE_CLIENT_ID=your_client_id
    OPENID_GITHUB_CLIENT_SECRET=your_secret
    
  2. Testing Use mock providers (e.g., Mockoon) to simulate OpenID responses during development. Override the provider class in tests:

    $this->app->bind(
        Dontdrinkandroot\OpenidBundle\OpenidProvider::class,
        App\Openid\MockProvider::class
    );
    
  3. Extending Functionality

    • Add custom claims to the user session:
      event(new OpenidAuthenticated($user, ['custom_claim' => $data]));
      
    • Override the default user resolver:
      $this->app->bind(
          Dontdrinkandroot\OpenidBundle\Services\UserResolver::class,
          App\Openid\CustomUserResolver::class
      );
      
  4. Performance

    • Cache provider configurations if they rarely change:
      $provider = Cache::remember('openid.provider.google', 86400, function () {
          return new GoogleProvider(config('openid.providers.google'));
      });
      
  5. Security

    • Validate the state parameter on callback to prevent CSRF attacks:
      if (!hash_equals($_SESSION['openid_state'], $_GET['state'])) {
          abort(403, 'Invalid state parameter.');
      }
      
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony