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

Oauth Bundle Laravel Package

den01101/oauth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require hwi/oauth-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        HWI\OAuthBundle\HWIOAuthBundle::class => ['all' => true],
    ];
    
  2. Configure Providers (e.g., GitHub): Add to config/packages/hwi_oauth.yaml:

    hwi_oauth:
        connect:
            account_connect_form_class: App\Form\ConnectForm
            account_connect_handler:
                class: HWI\Bundle\OAuthBundle\Security\Core\Authentication\Handler\OAuthAuthenticationSuccessHandler
            providers:
                github:
                    skip_user_setup: true
                    client_id: "your_client_id"
                    client_secret: "your_client_secret"
                    scope: "repo,gist"
    
  3. First Use Case:

    • Route users to /connect/github (or your provider).
    • After OAuth flow, users are authenticated via Symfony’s security system.
    • Access user data via $user->getOAuthToken() or $user->getOAuthRawAccessToken().

Where to Look First

  • Configuration: config/packages/hwi_oauth.yaml (or app/config/config.yml in older Symfony).
  • Security: security.yaml for firewall rules (e.g., anonymous: ~main).
  • Templates: templates/HWIOAuthBundle/Connect/connect.html.twig (customize login/logout buttons).
  • User Provider: Extend HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProvider if you need custom user mapping.

Implementation Patterns

Workflows

1. Basic OAuth Flow

  • Route Users: Use hwi_oauth_connect route (e.g., /connect/github).
  • Post-Auth Handling: Override OAuthAuthenticationSuccessHandler to redirect users or fetch additional data:
    // src/Security/OAuthSuccessHandler.php
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        // Fetch extra data (e.g., GitHub repos) and save to user entity.
        return new RedirectResponse('/dashboard');
    }
    
    Register in security.yaml:
    firewalls:
        main:
            oauth:
                resource_owners:
                    github: "/login/github-check"
                login_path: /login
                use_forward: false
                failure_path: /login
                oauth_user_provider:
                    class: App\Security\OAuthUserProvider
    

2. Custom User Mapping

Extend OAuthAwareUserProvider to map OAuth data to your user entity:

// src/Security/OAuthUserProvider.php
class OAuthUserProvider extends OAuthAwareUserProvider
{
    public function loadUserByOAuthUserResponse(OAuthUserResponse $response, $providerKey)
    {
        $email = $response->getEmail();
        $username = $response->getUsername();

        $user = $this->userManager->findUserBy(['email' => $email]);
        if (!$user) {
            $user = $this->userManager->createUser([
                'email' => $email,
                'username' => $username,
                'provider' => $providerKey,
                'provider_id' => $response->getId(),
            ]);
        }

        return $user;
    }
}

3. Multi-Provider Logins

Configure multiple providers in hwi_oauth.yaml:

providers:
    github:
        client_id: "..."
        client_secret: "..."
    google:
        client_id: "..."
        client_secret: "..."

Use hwi_oauth_connect route with provider suffix (e.g., /connect/github, /connect/google).

4. Token Refresh

For providers supporting it (e.g., Google), refresh tokens automatically:

hwi_oauth:
    connect:
        providers:
            google:
                options:
                    access_type: "offline"
                    approval_prompt: "force"

Extend OAuthUserResponse to handle refresh:

$token = $response->getAccessToken();
if ($token->isExpired()) {
    $token->refresh();
}

Integration Tips

  • Symfony Forms: Use HWI\Bundle\OAuthBundle\Form\Type\ConnectType for login forms.
  • API Calls: Use Guzzle or Symfony\Component\HttpClient with the OAuth token:
    $client = new Client();
    $response = $client->request('GET', 'https://api.github.com/user/repos', [
        'auth' => [$user->getOAuthToken(), 'x-oauth-basic']
    ]);
    
  • User Entity: Add OAuth-specific fields to your user model:
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $provider;
    
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $provider_id;
    
    /**
     * @ORM\Column(type="json", nullable=true)
     */
    private $oauth_data;
    
  • Logout: Use hwi_oauth_logout route or clear tokens manually:
    $user->setOAuthToken(null);
    $user->setOAuthRawAccessToken(null);
    $this->entityManager->flush();
    

Gotchas and Tips

Pitfalls

  1. Token Storage:

    • By default, tokens are stored in the session. For long-lived tokens, store them in the database (extend OAuthUserResponse or use a custom user provider).
    • Fix: Override getAccessToken() in your user provider to fetch from DB:
      $token = $this->tokenRepository->findOneBy(['user' => $user, 'provider' => $providerKey]);
      
  2. CSRF Issues:

    • OAuth1.0a requires CSRF tokens. Ensure your client_id and client_secret are correctly set.
    • Fix: Verify skip_user_setup: false in config if using OAuth1.
  3. Provider-Specific Quirks:

    • Facebook: Requires default_graph_version (e.g., v13.0) in config.
    • Google: Needs access_type: offline for refresh tokens.
    • GitHub: Scope repo may require additional permissions.
    • Fix: Check provider docs and adjust scope in config.
  4. User Provider Conflicts:

    • If using FOSUserBundle, ensure OAuthUserProvider is loaded after FOSUserBundle's provider.
    • Fix: Order matters in security.yaml:
      providers:
          fos_userbundle:
              id: fos_user.user_provider.username_email
          hwi_oauth:
              id: hwi_oauth.user_provider
      
  5. Debugging:

    • Enable debug mode to see OAuth errors in logs.
    • Use bin/console debug:config hwi_oauth to inspect config.
    • Tip: For OAuth2, check Authorization Code flow vs. Implicit flow (deprecated).

Debugging Tips

  • Logs: Enable monolog to log OAuth responses:
    monolog:
        handlers:
            main:
                level: debug
    
  • Dumps: Use Symfony’s dump() or dd() in custom handlers to inspect $response:
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $user = $token->getUser();
        dump($user->getOAuthResponse()); // Inspect raw OAuth data
    }
    
  • Provider-Specific Tools:

Extension Points

  1. Custom Providers: Add unsupported providers by extending HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface:

    class CustomProviderResponse extends UserResponseInterface
    {
        public function getEmail()
        {
            return $this->response['email'];
        }
    }
    

    Register in services.yaml:

    services:
        App\OAuth\CustomProviderResponse:
            tags:
                - { name: hwi_oauth.user_response.class, provider: "custom" }
    
  2. Event Listeners: Listen to hwi_oauth.connect.success or hwi_oauth.connect.fail:

    // src/EventListener/OAuthListener.php
    class OAuthListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                'hwi_oauth.connect.success' => 'onConnectSuccess',
            ];
        }
    
        public function onConnectSuccess(ConnectEvent $event)
        {
            $user = $event->getUser();
    
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views