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

Relay Auth Bundle Laravel Package

dbp/relay-auth-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-auth-bundle
    

    Publish the configuration file:

    php artisan vendor:publish --provider="DBP\RelayAuthBundle\RelayAuthServiceProvider" --tag="config"
    
  2. Configuration Update config/relay-auth.php with your OIDC server details (e.g., issuer URL, client ID, client secret, and redirect URI). Example:

    'oidc' => [
        'issuer' => env('OIDC_ISSUER_URL'),
        'client_id' => env('OIDC_CLIENT_ID'),
        'client_secret' => env('OIDC_CLIENT_SECRET'),
        'redirect_uri' => env('OIDC_REDIRECT_URI'),
    ],
    
  3. First Use Case: Authenticate a User Use the RelayAuth facade to authenticate a user via OIDC:

    use DBP\RelayAuthBundle\Facades\RelayAuth;
    
    // Redirect user to OIDC provider for login
    $authUrl = RelayAuth::login();
    return redirect()->to($authUrl);
    
    // Handle callback after login
    $user = RelayAuth::handleCallback(request());
    
  4. Middleware Integration Add the auth.relay middleware to routes requiring authentication:

    Route::middleware(['auth.relay'])->group(function () {
        // Protected routes
    });
    

Implementation Patterns

Workflows

  1. OIDC Authentication Flow

    • Login: Redirect users to the OIDC provider using RelayAuth::login().
    • Callback: Handle the OIDC callback with RelayAuth::handleCallback($request).
    • User Session: The bundle automatically creates or updates a Laravel session for the authenticated user.
  2. User Management

    • Create/Update Users: Use the RelayAuth::createOrUpdateUser($idToken) method to sync user data from the OIDC provider to your Laravel users table.
    • Custom Claims Handling: Extend the UserMapper class to handle custom claims from the OIDC token:
      // app/Providers/RelayAuthServiceProvider.php
      public function boot()
      {
          RelayAuth::extendUserMapper(function ($mapper) {
              $mapper->mapCustomClaim('custom_claim', 'user_custom_field');
          });
      }
      
  3. API Gateway Integration

    • Token Validation: Validate incoming API requests using the RelayAuth::validateToken($token) method in middleware or controllers.
    • Relay-Specific Logic: Use the RelayAuth::getRelayUser() helper to access the authenticated user in a Relay context (e.g., for API gateways).

Integration Tips

  • Laravel Passport/ Sanctum: Combine with Laravel's built-in auth systems for hybrid authentication:
    // Sync OIDC user with Sanctum/Passport
    $user = RelayAuth::createOrUpdateUser($idToken);
    $token = $user->createToken('Relay Token')->accessToken;
    
  • Custom Providers: Override the default OIDC provider by binding a custom League\OAuth2\Client\Provider\GenericProvider instance:
    RelayAuth::setOidcProvider($customProvider);
    
  • Logging: Enable debug logging in config/relay-auth.php for troubleshooting:
    'debug' => env('RELAY_AUTH_DEBUG', false),
    

Gotchas and Tips

Pitfalls

  1. Callback URL Mismatch

    • Ensure the redirect_uri in config/relay-auth.php matches the URL configured in your OIDC provider. Mismatches will cause authentication failures.
    • Fix: Double-check the OIDC_REDIRECT_URI in your .env file and OIDC provider settings.
  2. Token Expiry Handling

    • The bundle does not automatically refresh expired tokens. Implement a middleware to validate token expiry:
      use DBP\RelayAuthBundle\Facades\RelayAuth;
      
      public function handle($request, Closure $next)
      {
          if (!RelayAuth::validateToken($request->bearerToken())) {
              return response()->json(['error' => 'Unauthorized'], 401);
          }
          return $next($request);
      }
      
  3. User Sync Conflicts

    • If the OIDC provider returns a sub claim that doesn’t map cleanly to your users table, the createOrUpdateUser method may fail.
    • Fix: Customize the UserMapper to handle edge cases:
      RelayAuth::extendUserMapper(function ($mapper) {
          $mapper->mapIdClaim('custom_id_field'); // Override default 'sub' claim
      });
      
  4. Session Fixation

    • Ensure your Laravel session configuration uses a secure, HTTP-only cookie to prevent session fixation attacks:
      'session' => [
          'driver' => 'cookie',
          'cookie' => 'secure',
      ],
      

Debugging

  • Enable Debug Mode: Set 'debug' => true in config/relay-auth.php to log detailed OIDC interactions.
  • Check Logs: Inspect storage/logs/laravel.log for OIDC errors (e.g., invalid tokens, network issues).
  • Test Locally: Use tools like oidcdebugger.com to validate your OIDC configuration before deploying.

Extension Points

  1. Custom User Model Override the default user model by binding a custom implementation:

    RelayAuth::setUserModel(App\Models\CustomUser::class);
    
  2. Event Listeners Listen to OIDC events (e.g., oidc.login.success) for custom logic:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'DBP\RelayAuthBundle\Events\OidcLoginSuccess' => [
            'App\Listeners\LogOidcLogin',
        ],
    ];
    
  3. Relay-Specific Extensions Extend the RelayAuth facade to add Relay-specific methods:

    // app/Providers/RelayAuthServiceProvider.php
    public function boot()
    {
        RelayAuth::extend(function ($auth) {
            $auth->getRelayContext = function () {
                return [
                    'user_id' => auth()->id(),
                    'scopes' => auth()->user()->scopes,
                ];
            };
        });
    }
    
  4. Testing Mock the OIDC provider in tests using a library like mockery or league/oauth2-server:

    $provider = Mockery::mock('overload', 'League\OAuth2\Client\Provider\GenericProvider');
    RelayAuth::setOidcProvider($provider);
    

```markdown
### Config Quirks
- **Environment Variables**: The bundle expects specific env vars (`OIDC_ISSUER_URL`, `OIDC_CLIENT_ID`, etc.). Use placeholders like `env('OIDC_ISSUER_URL')` in `config/relay-auth.php` to avoid hardcoding.
- **Caching**: The bundle caches OIDC configuration by default. Clear the cache (`php artisan cache:clear`) if you update the config without seeing changes.
- **HTTPS Requirement**: The OIDC provider may reject requests over HTTP. Ensure your Laravel app uses HTTPS in production:
  ```php
  'trusted_proxies' => [
      '*',
  ],
  'secure' => env('APP_ENV') === 'production',
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.
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
spatie/flare-daemon-runtime