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

Simple Oauth Bundle Laravel Package

druidvav/simple-oauth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require druidvav/simple-oauth-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Druidvav\SimpleOAuthBundle\DruidvavSimpleOAuthBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console druidvav:simple-oauth:install
    

    Edit config/packages/druidvav_simple_oauth.yaml to define your OAuth providers (e.g., Google, GitHub).

  3. First Use Case Add a route to trigger OAuth login (e.g., in config/routes.yaml):

    simple_oauth_connect:
        path: /connect/{provider}
        controller: Druidvav\SimpleOAuthBundle\Controller\OAuthController::connectAction
    

    Use the route in a template:

    <a href="{{ path('simple_oauth_connect', {'provider': 'google'}) }}">Login with Google</a>
    

Implementation Patterns

Workflow: OAuth Login Flow

  1. Redirect to Provider Use the connectAction to redirect users to the OAuth provider (e.g., /connect/google).

  2. Callback Handling Configure the callback route in routes.yaml:

    simple_oauth_callback:
        path: /connect/{provider}/callback
        controller: Druidvav\SimpleOAuthBundle\Controller\OAuthController::callbackAction
    

    The bundle automatically handles the OAuth callback, validates the response, and creates a user if needed.

  3. User Management Extend the bundle’s UserProvider (e.g., src/Service/OAuthUserProvider.php) to customize user creation/update logic:

    use Druidvav\SimpleOAuthBundle\Service\UserProviderInterface;
    
    class OAuthUserProvider implements UserProviderInterface {
        public function getUserFromOAuthData($provider, array $data) {
            // Custom logic to fetch/update user
            return $user;
        }
    }
    

    Register the service in services.yaml:

    services:
        Druidvav\SimpleOAuthBundle\Service\UserProviderInterface: '@App\Service\OAuthUserProvider'
    
  4. Session Handling The bundle stores OAuth tokens in the session. Access them via:

    $tokens = $this->get('session')->get('oauth_tokens');
    

Integration Tips

  • Symfony Security Component: Integrate with Symfony’s security system by extending AbstractGuardAuthenticator to validate OAuth tokens.
  • API Clients: Use the OAuthClient service to manually fetch data from providers:
    $client = $this->get('druidvav_simple_oauth.oauth_client');
    $data = $client->fetch('google', 'userinfo');
    
  • Multi-Provider Support: Define multiple providers in the config and reuse the same workflow for each.

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Version The bundle was last updated in 2016 and may not support modern Symfony (5.4+/6.x). Test thoroughly or fork the bundle for compatibility.

  2. Session Storage OAuth tokens are stored in the session by default. For distributed systems, consider using a database or cache (e.g., Redis) instead.

  3. Provider-Specific Quirks Some providers (e.g., GitHub) require additional scopes or parameters. Check the provider’s documentation and adjust the config accordingly:

    providers:
        github:
            client_id: '%env(GITHUB_CLIENT_ID)%'
            client_secret: '%env(GITHUB_CLIENT_SECRET)%'
            scope: ['user:email', 'read:org']  # Custom scopes
    
  4. CSRF Protection The callback route may trigger CSRF errors if not configured properly. Ensure your firewall allows the callback path:

    # config/packages/security.yaml
    firewalls:
        main:
            pattern: ^/
            form_login:
                check_path: /login_check
            # Allow OAuth callbacks
            anonymous: lazy
            context: main
    

Debugging

  • Enable Debug Mode: Set debug: true in the config to log OAuth responses:
    druidvav_simple_oauth:
        debug: true
    
  • Check Logs: Errors during OAuth flow will appear in var/log/dev.log. Look for Druidvav\SimpleOAuthBundle entries.
  • Provider-Specific Errors: If a provider fails silently, inspect the raw response by extending the OAuthClient service.

Extension Points

  1. Custom User Entity Override the UserProvider to map OAuth data to your custom user entity:

    public function getUserFromOAuthData($provider, array $data) {
        $user = $this->userRepository->findOneBy(['email' => $data['email']]);
        if (!$user) {
            $user = new YourUserEntity();
            $user->setEmail($data['email']);
            $user->setProvider($provider);
            $user->setProviderId($data['id']);
            $this->userRepository->save($user);
        }
        return $user;
    }
    
  2. Token Storage Replace the session-based token storage by implementing a custom TokenStorageInterface:

    use Druidvav\SimpleOAuthBundle\Service\TokenStorageInterface;
    
    class DatabaseTokenStorage implements TokenStorageInterface {
        public function store($provider, array $tokens) { /* Save to DB */ }
        public function get($provider) { /* Fetch from DB */ }
    }
    

    Register it in services.yaml:

    services:
        Druidvav\SimpleOAuthBundle\Service\TokenStorageInterface: '@App\Service\DatabaseTokenStorage'
    
  3. Event Listeners Listen for OAuth events (e.g., oauth.login.success) to trigger post-login actions:

    use Druidvav\SimpleOAuthBundle\Event\OAuthEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class OAuthSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                OAuthEvents::LOGIN_SUCCESS => 'onLoginSuccess',
            ];
        }
    
        public function onLoginSuccess(OAuthEvent $event) {
            // Custom logic (e.g., send welcome email)
        }
    }
    
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