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

Oauth2 Client Bundle Laravel Package

knpuniversity/oauth2-client-bundle

Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require knpuniversity/oauth2-client-bundle
    

    Add the bundle to config/bundles.php (Symfony) or config/app.php (Laravel via Symfony bridge):

    KnpU\OAuth2ClientBundle\KnpUOAuth2ClientBundle::class => ['all' => true],
    
  2. Configure Providers Edit config/packages/knpu_oauth2_client.yaml (Symfony) or config/oauth.php (Laravel):

    knpu_oauth2_client:
        clients:
            github:
                type: github
                client_id: '%env(GITHUB_CLIENT_ID)%'
                client_secret: '%env(GITHUB_CLIENT_SECRET)%'
                redirect_route: connect_github_check
    
  3. First Use Case: Login with GitHub

    • Generate a route for OAuth initiation:
      # config/routes.yaml
      connect_github:
          path: /connect/github
          controller: KnpU\OAuth2ClientBundle\Controller\ConnectController::connectAction
      
    • Use the OAuth2Authenticator in a controller:
      use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
      use KnpU\OAuth2ClientBundle\Client\Provider\GithubClient;
      
      public function login(ClientRegistry $clientRegistry)
      {
          return $clientRegistry->getClient('github')->redirect();
      }
      

Implementation Patterns

Common Workflows

  1. User Authentication Flow

    • Redirect to Provider:
      $client = $clientRegistry->getClient('github');
      return $client->redirect();
      
    • Handle Callback:
      $user = $client->fetchUser();
      // Save to DB or create session
      
  2. Multi-Provider Support Dynamically register providers in config/oauth.php:

    'providers' => [
        'github' => [
            'type' => 'github',
            'client_id' => env('GITHUB_ID'),
            'client_secret' => env('GITHUB_SECRET'),
        ],
        'google' => [
            'type' => 'google',
            'client_id' => env('GOOGLE_ID'),
            'client_secret' => env('GOOGLE_SECRET'),
        ],
    ],
    
  3. Custom User Mapping Extend User entity or use a mapper:

    use KnpU\OAuth2ClientBundle\Client\Provider\GithubUser;
    
    public function connectGithub(GithubUser $user)
    {
        $account = $this->userManager->findBy(['email' => $user->getEmail()]);
        if (!$account) {
            $account = $this->userManager->create([
                'email' => $user->getEmail(),
                'name' => $user->getUsername(),
            ]);
        }
        return $account;
    }
    
  4. State Management Use the built-in state system to prevent CSRF:

    # config/packages/knpu_oauth2_client.yaml
    knpu_oauth2_client:
        clients:
            github:
                state: true  # Default: true
    

Integration Tips

  • Laravel-Specific: Use symfony/bridge to integrate with Laravel’s auth system:
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use KnpU\OAuth2ClientBundle\Client\OAuth2Client;
    
    public function handleOAuth(OAuth2Client $client)
    {
        $user = $client->fetchUser();
        Auth::loginUsingId($user->getId()); // Custom logic
        return redirect('/dashboard');
    }
    
  • Laravel Passport: Combine with OAuth2 for API auth:
    // After OAuth login, issue a Passport token
    $token = $user->createToken('oauth_token')->accessToken;
    

Gotchas and Tips

Pitfalls

  1. State Mismatch Errors

    • Cause: Missing or invalid state parameter in redirects.
    • Fix: Ensure state: true in config and regenerate .env secrets if needed.
  2. Provider-Specific Quirks

    • GitHub: Requires redirect_uri to match exactly (including trailing slashes).
    • Google: Needs scopes explicitly defined:
      google:
          scopes: ['email', 'profile']
      
  3. Session Handling

    • Symfony: Uses Symfony’s session; ensure session.storage.handler_id is set.
    • Laravel: May require manual session binding:
      session(['oauth_state' => $client->getState()]);
      
  4. Token Expiry

    • Refresh tokens silently fail if not handled. Use refreshToken():
      $client->refreshToken($refreshToken);
      

Debugging Tips

  • Enable Debug Mode:
    knpu_oauth2_client:
        debug: true  # Logs OAuth requests/responses
    
  • Check Provider Docs: Some providers (e.g., LinkedIn) require additional scopes or app approval.
  • Inspect Redirect URIs: Use dd($client->getRedirectUri()) to verify URLs.

Extension Points

  1. Custom Providers Extend OAuth2Client for unsupported providers:

    use KnpU\OAuth2ClientBundle\Client\Provider\GenericProvider;
    
    class CustomProvider extends GenericProvider {
        public function getBaseUrl() { return 'https://custom-api.com'; }
        public function getResourceOwnerDetailsUrl($token) { ... }
    }
    
  2. Event Listeners Listen to KnpUOAuth2ClientBundle.Event\AuthEvent for post-login actions:

    use KnpU\OAuth2ClientBundle\Event\AuthEvent;
    
    public function onAuth(AuthEvent $event) {
        $user = $event->getUser();
        // Custom logic (e.g., sync roles)
    }
    
  3. Laravel Service Providers Bind the registry to Laravel’s container:

    public function register()
    {
        $this->app->bind('knpu.oauth2.client.registry', function ($app) {
            return new ClientRegistry([...], $app['http_client']);
        });
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware