Weave 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

Oauth Client Bundle Laravel Package

da/oauth-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require gnuckorg/da-oauth-client-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Gnuckorg\DaOAuthClientBundle\GnuckorgDaOAuthClientBundle::class => ['all' => true],
    ];
    
  2. Configuration: Update config/packages/gnuckorg_da_oauth_client.yaml with your OAuth provider details (e.g., client ID, secret, auth URL):

    gnuckorg_da_oauth_client:
        clients:
            my_provider:
                type: "oauth2"
                client_id: "%env(OAUTH_CLIENT_ID)%"
                client_secret: "%env(OAUTH_CLIENT_SECRET)%"
                auth_url: "https://provider.com/oauth/authorize"
                access_token_url: "https://provider.com/oauth/token"
                scope: ["openid", "profile"]
    
  3. First Use Case: Inject the OAuth client service and authenticate a user:

    use Gnuckorg\DaOAuthClientBundle\Client\OAuthClientInterface;
    
    public function __construct(OAuthClientInterface $oauthClient) {
        $this->oauthClient = $oauthClient;
    }
    
    public function login(Request $request) {
        $authUrl = $this->oauthClient->getAuthenticationUrl('my_provider');
        // Redirect user to $authUrl
    }
    
    public function callback(Request $request) {
        $user = $this->oauthClient->getUserFromAccessToken('my_provider', $request->query->get('code'));
        // Handle user data (e.g., save to session or database)
    }
    
  4. Routing: Add routes in config/routes.yaml:

    gnuckorg_da_oauth_client_connect:
        path: /connect/{provider}
        controller: Gnuckorg\DaOAuthClientBundle\Controller\ConnectController::connectAction
    gnuckorg_da_oauth_client_callback:
        path: /connect/{provider}/callback
        controller: Gnuckorg\DaOAuthClientBundle\Controller\ConnectController::callbackAction
    

Implementation Patterns

Workflows

  1. Authentication Flow:

    • Step 1: Redirect user to provider’s auth URL via $oauthClient->getAuthenticationUrl('provider').
    • Step 2: Handle callback at /connect/{provider}/callback to exchange code for an access_token.
    • Step 3: Fetch user data with $oauthClient->getUserFromAccessToken('provider', $accessToken).
  2. User Data Handling:

    • Use the User object returned by getUserFromAccessToken to populate your user model:
      $userData = $oauthClient->getUserFromAccessToken('my_provider', $accessToken);
      $yourUser = new YourUserEntity();
      $yourUser->setEmail($userData->getEmail());
      $yourUser->setName($userData->getFirstName() . ' ' . $userData->getLastName());
      
  3. Multi-Provider Support:

    • Configure multiple providers in gnuckorg_da_oauth_client.yaml and switch between them dynamically:
      $provider = $request->get('provider'); // e.g., 'google', 'github'
      $authUrl = $this->oauthClient->getAuthenticationUrl($provider);
      
  4. Token Refresh:

    • Use $oauthClient->refreshAccessToken('provider', $refreshToken) to handle expired tokens.

Integration Tips

  • Symfony Security: Integrate with Symfony’s security system by creating a custom UserProvider or Authenticator:

    public function loadUserByOAuthToken($token, $provider) {
        $userData = $this->oauthClient->getUserFromAccessToken($provider, $token);
        return $this->userRepository->findOrCreateByOAuthData($userData);
    }
    
  • State Parameter: Always include a state parameter in the auth URL to prevent CSRF:

    $state = bin2hex(random_bytes(32));
    $request->getSession()->set('oauth_state', $state);
    $authUrl = $this->oauthClient->getAuthenticationUrl('my_provider', ['state' => $state]);
    

    Verify the state in the callback to ensure request integrity.

  • Custom User Data Mapping: Extend the Gnuckorg\DaOAuthClientBundle\User\User class to map provider-specific fields to your user model:

    class CustomUser extends User {
        public function getCustomField() {
            return $this->get('custom_field_from_provider');
        }
    }
    
  • Logging: Log OAuth events (e.g., token exchange failures) for debugging:

    try {
        $user = $this->oauthClient->getUserFromAccessToken('provider', $code);
    } catch (\Exception $e) {
        $this->logger->error('OAuth token exchange failed', ['exception' => $e]);
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Bundle:

    • The bundle is last updated in 2015 and relies on HWIOAuthBundle, which is also outdated. Ensure compatibility with your Symfony version (tested up to Symfony 3.x).
    • Mitigation: Fork the repository or use a modern alternative like league/oauth2-client if critical features are missing.
  2. Missing Documentation:

    • The README and inline docs are sparse. Key methods like getUserFromAccessToken lack examples for handling provider-specific responses.
    • Tip: Inspect the HWIOAuthBundle docs for similar patterns, as this bundle extends it.
  3. State Parameter Handling:

    • The bundle does not enforce state validation by default. Always implement manual checks in the callback to prevent CSRF.
    • Example:
      $requestState = $request->query->get('state');
      $sessionState = $request->getSession()->get('oauth_state');
      if ($requestState !== $sessionState) {
          throw new \RuntimeException('Invalid state parameter.');
      }
      
  4. Token Storage:

    • The bundle does not persist access/refresh tokens automatically. Manually store them (e.g., in the user entity or database) for future use.
    • Tip: Use a trait or service to manage token storage:
      class UserTokenManager {
          public function saveToken(User $user, string $token, string $provider) {
              $user->setOAuthToken($token, $provider);
              $this->userRepository->save($user);
          }
      }
      
  5. Provider-Specific Quirks:

    • Some providers (e.g., Google, GitHub) require additional scopes or parameters. Configure these in the scope or options arrays:
      gnuckorg_da_oauth_client:
          clients:
              google:
                  options:
                      display: "popup" # For Google's popup auth
      
  6. Error Handling:

    • OAuth errors (e.g., invalid_grant) may not bubble up predictably. Wrap calls in try-catch blocks:
      try {
          $user = $this->oauthClient->getUserFromAccessToken('provider', $code);
      } catch (\HWI\Bundle\OAuthBundle\OAuth\Exception\AccountNotLinkedException $e) {
          // Handle account linking (e.g., redirect to manual registration)
      }
      

Debugging

  1. Enable HWIOAuthBundle Debugging: Add to config/packages/dev/gnuckorg_da_oauth_client.yaml:

    gnuckorg_da_oauth_client:
        debug: true
    

    This logs OAuth requests/responses to var/log/dev.log.

  2. Check Provider Responses:

    • Use a tool like Postman to manually test the OAuth flow with your provider’s endpoints. Compare responses to those received by the bundle.
  3. Symfony Profiler:

Extension Points

  1. Custom User Provider: Override the default user provider to transform OAuth data:

    # config/packages/gnuckorg_da_oauth_client.yaml
    gnuckorg_da_oauth_client:
        user_provider: App\Service\CustomOAuthUserProvider
    

    Implement Gnuckorg\DaOAuthClientBundle\User\UserProviderInterface.

  2. Add New OAuth Providers: Extend the bundle by adding new provider configurations dynamically:

    $this->container->get('gnuckorg_da_oauth_client.client_manager')->addClient('custom_provider', [
        'type
    
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.
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels