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

chaplean/oauth-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require hwi/oauth-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        HWI\Bundle\OAuthBundle\HWIOAuthBundle::class => ['all' => true],
    ];
    
  2. Configure Providers Edit config/packages/hwi_oauth.yaml (or create it):

    hwi_oauth:
        connect:
            account_connector: your_app.user.provider.oauth # Custom service
            # Example for GitHub:
            github:
                skip_if_logged_in: true
                client_id: "your_client_id"
                client_secret: "your_client_secret"
                scope: "read:user user:email"
    
  3. First Use Case: Login with GitHub

    • Add a route to config/routes.yaml:
      hwi_oauth_connect:
          resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"
          prefix: /connect
      
    • Generate a login button in a Twig template:
      <a href="{{ path('hwi_oauth_connect_github') }}">Login with GitHub</a>
      

Implementation Patterns

Workflow: OAuth Login Flow

  1. User Initiates Login Redirect to /connect/github (or other provider).
  2. Provider Redirect HWI handles the OAuth handshake (authorization code/token exchange).
  3. User Data Fetch After successful auth, HWI fetches user data (e.g., email, name) from the provider.
  4. Custom User Mapping Use account_connector service to map provider data to your User entity:
    // src/User/OAuthUserProvider.php
    namespace App\User;
    
    use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
    use Symfony\Component\Security\Core\User\UserInterface;
    
    class OAuthUserProvider implements \HWI\Bundle\OAuthBundle\Connect\AccountConnectorInterface
    {
        public function connect(UserResponseInterface $response, $accountLifetime = null)
        {
            $user = new YourUser();
            $user->setEmail($response->getEmail());
            $user->setUsername($response->getUsername());
            $user->addRole('ROLE_USER');
            return $user;
        }
    }
    

Integration Tips

  • Security: Use skip_if_logged_in to prevent logged-in users from re-authenticating.
  • Scopes: Request minimal scopes (e.g., email instead of user).
  • Multi-Provider: Configure multiple providers in hwi_oauth.yaml:
    github: { ... }
    google: { ... }
    
  • Custom Routes: Override default routes in routing.yaml:
    hwi_oauth_connect:
        path: /login/oauth/{provider}
    

Handling User Data

  • Access provider data in your account_connector:
    $response->getEmail();
    $response->getFirstName();
    $response->getLastName();
    $response->getAccessToken(); // For API calls later
    
  • Store the access token in your User entity for future API requests:
    $user->setAccessToken($response->getAccessToken());
    

Gotchas and Tips

Pitfalls

  1. Missing account_connector Forgetting to configure account_connector will throw: No account connector found for provider "github". Fix: Define the service in services.yaml:

    services:
        your_app.user.provider.oauth:
            class: App\User\OAuthUserProvider
            tags:
                - { name: hwi_oauth.connect.account_connector, connector: github }
    
  2. CORS Issues with API Calls If using the access token to call provider APIs, ensure:

    • The token has the correct scope.
    • The provider’s API endpoint allows your domain (check CORS headers).
  3. Token Expiry OAuth2 tokens expire. Implement token refresh logic in your account_connector or a separate service:

    if ($user->getAccessTokenExpiresAt() < new \DateTime()) {
        $newToken = $this->refreshToken($user->getRefreshToken());
        $user->setAccessToken($newToken);
    }
    
  4. Provider-Specific Quirks

    • GitHub: Requires user:email scope for email access.
    • Google: May require additional OAuth consent screen setup in Google Cloud Console.
    • Facebook: Uses fb as the route prefix by default (not facebook).

Debugging

  • Enable Debugging Set debug: true in hwi_oauth.yaml to log OAuth responses:
    hwi_oauth:
        debug: true
    
  • Check Provider Logs Look for errors in var/log/dev.log (Symfony) or storage/logs/laravel.log (Laravel). Example error:
    Client error: `GET https://api.github.com/user` resulted in a `401 Unauthorized` response
    
    Fix: Verify client_id, client_secret, and scopes.

Extension Points

  1. Custom User Entity Extend the User entity to include OAuth-specific fields:

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $oauthProvider;
    private $oauthProviderId;
    private $accessToken;
    private $accessTokenExpiresAt;
    
  2. Post-Auth Redirects Use Symfony’s security.authentication.success_handler to redirect users after login:

    # config/packages/security.yaml
    security:
        firewalls:
            main:
                form_login:
                    success_handler: App\Security\OAuthSuccessHandler
    
    // src/Security/OAuthSuccessHandler.php
    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        $targetUrl = $this->determineTargetUrl($request);
        return new RedirectResponse($targetUrl);
    }
    
  3. API Client Integration Use the stored access token to call provider APIs:

    $client = new \GuzzleHttp\Client();
    $response = $client->get('https://api.github.com/user/repos', [
        'auth' => [$user->getEmail(), $user->getAccessToken()],
    ]);
    
  4. Dynamic Provider Configuration Load provider configs from a database or environment variables:

    # .env
    GITHUB_CLIENT_ID=your_id
    GITHUB_CLIENT_SECRET=your_secret
    
    // In a service
    $config = [
        'github' => [
            'client_id' => $_ENV['GITHUB_CLIENT_ID'],
            'client_secret' => $_ENV['GITHUB_CLIENT_SECRET'],
        ],
    ];
    

Performance Tips

  • Cache User Data Avoid repeated API calls for the same user by caching their data in the User entity or Redis.
  • Lazy-Load Provider Data Fetch provider data only when needed (e.g., in a User entity getter).
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