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 Connect Bundle Laravel Package

daanvanberkel/openid-connect-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require daanvanberkel/openid-connect-bundle
    

    Add to config/bundles.php:

    Daanvanberkel\OpenidConnectBundle\DaanvanberkelOpenidConnectBundle::class => ['all' => true],
    
  2. Configuration: Publish the default config:

    php bin/console daanvanberkel:openid-connect:install
    

    Edit config/packages/daanvanberkel_openid_connect.yaml with your provider details (e.g., Auth0, Okta, or custom OIDC endpoint).

  3. First Use Case: Secure a route with OIDC authentication:

    # config/routes.yaml
    secured_route:
        path: /dashboard
        controller: App\Controller\DashboardController::index
        methods: GET
        requirements:
            role: ROLE_USER
    

    The bundle automatically handles redirects to the OIDC provider and token validation.


Implementation Patterns

Core Workflows

  1. Authentication Flow:

    • Use the authenticate route (default: /login/openid-connect) for user login.
    • The bundle handles:
      • Redirect to OIDC provider.
      • Token exchange (authorization code flow).
      • User association (via UserProvider interface).
  2. User Provider Integration: Implement Daanvanberkel\OpenidConnectBundle\Security\User\UserProviderInterface to map OIDC claims to your user entity:

    class CustomUserProvider implements UserProviderInterface
    {
        public function loadUserById(string $id): UserInterface
        {
            // Fetch user from DB or create if needed.
        }
    
        public function loadUserFromOidc(array $claims): UserInterface
        {
            // Map claims (e.g., `sub`, `email`) to your user entity.
        }
    }
    

    Register it in config:

    daanvanberkel_openid_connect:
        user_provider: App\Security\User\CustomUserProvider
    
  3. Role Assignment: Dynamically assign roles based on OIDC claims:

    daanvanberkel_openid_connect:
        role_claim: "https://example.com/roles"  # Custom claim for roles
    
  4. Logout: Extend the default logout to clear OIDC sessions:

    // src/EventListener/OpenidConnectLogoutListener.php
    use Daanvanberkel\OpenidConnectBundle\Event\OpenidConnectLogoutEvent;
    
    class OpenidConnectLogoutListener
    {
        public function onLogout(OpenidConnectLogoutEvent $event)
        {
            // Revoke tokens or clean up state.
        }
    }
    

    Register in services.yaml:

    services:
        App\EventListener\OpenidConnectLogoutListener:
            tags:
                - { name: kernel.event_listener, event: openid_connect.logout }
    

Integration Tips

  • Symfony Security: The bundle integrates with Symfony’s security component. Use ROLE_USER or custom roles in firewalls:
    security:
        firewalls:
            main:
                oidc: true
                logout:
                    path: /logout
                    target: /login
    
  • Custom Claims: Extend the ClaimMapper to transform provider claims:
    class CustomClaimMapper extends ClaimMapper
    {
        public function map(array $claims): array
        {
            $claims['custom_field'] = $claims['raw']['custom_claim'] ?? null;
            return parent::map($claims);
        }
    }
    
    Configure in services.yaml:
    daanvanberkel_openid_connect.claim_mapper: '@App\Security\CustomClaimMapper'
    

Gotchas and Tips

Pitfalls

  1. Token Validation:

    • Ensure your OIDC provider’s issuer URL and public keys are correctly configured. Misconfigurations lead to InvalidIdToken exceptions.
    • Debug with:
      php bin/console debug:config daanvanberkel_openid_connect
      
  2. State Management:

    • The bundle uses Symfony’s CsrfTokenManager for state. If you customize the login route, ensure the state parameter is preserved in redirects.
  3. User Association:

    • If loadUserFromOidc returns null, the user is not linked. Verify the user_provider is correctly implemented and the claims match your user model.
  4. CORS Issues:

    • For SPAs or APIs, configure CORS headers manually in the bundle’s EventListener or middleware, as the bundle doesn’t handle CORS by default.

Debugging

  • Enable Verbose Logging:

    daanvanberkel_openid_connect:
        debug: true
    

    Logs appear in var/log/dev.log.

  • Token Inspection: Dump the decoded ID token in a controller:

    use Daanvanberkel\OpenidConnectBundle\Security\OpenidConnectAuthenticator;
    
    public function debugToken(OpenidConnectAuthenticator $authenticator)
    {
        $token = $authenticator->getUser()->getOidcToken();
        var_dump($token->getClaims());
    }
    

Extension Points

  1. Custom Authenticators: Extend OpenidConnectAuthenticator to add pre/post-auth logic:

    class CustomAuthenticator extends OpenidConnectAuthenticator
    {
        protected function getOidcUser(array $claims, Token $token)
        {
            // Custom user logic.
        }
    }
    

    Register in security.yaml:

    security:
        firewalls:
            main:
                oidc:
                    authenticator: App\Security\CustomAuthenticator
    
  2. Provider-Specific Logic: Use the OpenidConnectProviderEvent to modify provider configurations dynamically:

    class DynamicProviderConfigListener
    {
        public function onProviderConfig(OpenidConnectProviderEvent $event)
        {
            if ($event->getProviderName() === 'auth0') {
                $event->setConfig(['custom' => 'value']);
            }
        }
    }
    

    Tag the service:

    services:
        App\EventListener\DynamicProviderConfigListener:
            tags:
                - { name: kernel.event_listener, event: openid_connect.provider_config }
    
  3. Nonce Handling: For PKCE flows, customize the NonceManager to store/validate nonces in your preferred storage (e.g., Redis):

    class RedisNonceManager implements NonceManagerInterface
    {
        public function generateNonce(): string
        {
            return bin2hex(random_bytes(32));
        }
    
        public function isValid(string $nonce): bool
        {
            // Check Redis.
        }
    }
    

    Bind it in services.yaml:

    daanvanberkel_openid_connect.nonce_manager: '@App\Security\RedisNonceManager'
    

Config Quirks

  • Default Scopes: The bundle uses openid email profile by default. Override in config:
    daanvanberkel_openid_connect:
        scopes: ["openid", "email", "custom_scope"]
    
  • JWKS Refresh: The bundle refreshes JWKS keys every 24 hours by default. Adjust with:
    daanvanberkel_openid_connect:
        jwks_refresh_interval: 3600  # 1 hour
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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