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

hwi/oauth-bundle

Symfony bundle for OAuth1.0a/OAuth2 login and user authentication. Supports Symfony 6.4–8.0 (PHP 8.3+) and integrates dozens of providers (Google, GitHub, Facebook, Apple, LinkedIn, Azure, Keycloak, etc.).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for OAuth2 (e.g., Google)

  1. Install the Bundle

    composer require hwi/oauth-bundle
    
  2. Configure a Resource Owner (config/packages/hwi_oauth.yaml):

    hwi_oauth:
        resource_owners:
            google:
                type:                google
                client_id:           "%env(GOOGLE_CLIENT_ID)%"
                client_secret:       "%env(GOOGLE_CLIENT_SECRET)%"
                scope:               "email profile openid"
    
  3. Enable the Route (config/routes.yaml):

    hwi_oauth_connect:
        resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"
        prefix:   /login
    
  4. Create a Security Firewall (config/packages/security.yaml):

    firewalls:
        main:
            oauth:
                resource_owners:
                    google:            "/login/check-google"
                login_path:        /login
                failure_path:      /login
                oauth_user_provider:
                    service:           hwi_oauth.user.provider
    
  5. First Use Case: Login Button Add a link to /login/check-google in your template. After successful OAuth, the user is authenticated and redirected to the configured default_target_path.


Implementation Patterns

1. Multi-Provider Authentication

Configure multiple providers in hwi_oauth.yaml and expose them in the firewall:

firewalls:
    main:
        oauth:
            resource_owners:
                google:  "/login/check-google"
                github:  "/login/check-github"

2. Custom User Provider

Extend HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUserProvider to map OAuth data to your User entity:

// src/Security/OAuthUserProvider.php
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUserProvider as BaseOAuthUserProvider;

class OAuthUserProvider extends BaseOAuthUserProvider
{
    public function connect(UserInterface $user, UserProviderInterface $userProvider, $accountIdentifier)
    {
        // Custom logic to link OAuth accounts to your User entity
    }

    public function loadUserByOAuthUserClass($class)
    {
        return new YourUserEntity();
    }
}

Register the service in config/services.yaml:

services:
    App\Security\OAuthUserProvider:
        arguments:
            - '@fos_user.user_manager' # or your user manager
            - '@hwi_oauth.security.oauth_utils'
        tags:
            - { name: hwi_oauth.user.provider }

3. Token Refresh Workflow

For providers supporting token refresh (e.g., Google), implement a service to refresh tokens:

// src/Service/OAuthTokenRefresher.php
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;

class OAuthTokenRefresher
{
    public function refreshToken(UserResponseInterface $response)
    {
        $client = $response->getOAuthWebService()->getClient();
        $client->refreshToken($response->getAccessToken());
        return $client->getAccessToken();
    }
}

4. Dynamic Scopes

Use placeholders or environment variables for scopes to avoid hardcoding:

hwi_oauth:
    resource_owners:
        github:
            scope: "user:email repo %env(GITHUB_SCOPE_EXTRA)%"

5. Post-Authentication Logic

Use the hwi_oauth.on.connect event to trigger actions after login:

// src/EventListener/OAuthConnectListener.php
use HWI\Bundle\OAuthBundle\Event\ConnectEvent;

class OAuthConnectListener
{
    public function onConnect(ConnectEvent $event)
    {
        $user = $event->getUser();
        // Example: Sync user data or log the event
    }
}

Register the listener in config/services.yaml:

services:
    App\EventListener\OAuthConnectListener:
        tags:
            - { name: kernel.event_listener, event: hwi_oauth.on.connect, method: onConnect }

Gotchas and Tips

1. Configuration Quirks

  • Environment Variables: Always use %env() for client_id and client_secret to avoid exposing secrets in config files.
  • Base URL for Self-Hosted Providers: For providers like Jira or custom OAuth2 servers, ensure base_url is correctly set (e.g., https://your-jira-instance.com).
  • Scope Validation: Some providers (e.g., Google) require specific scopes. Validate these in the provider’s documentation.

2. Debugging Common Issues

  • Redirect URI Mismatch: Ensure the redirect_uri in your OAuth provider settings matches the one configured in Symfony (default: http://localhost:8000/connect/{resource_owner}/check).
  • CSRF Token Errors: If using OAuth1.0a (e.g., Twitter), ensure the state parameter is included in the request.
  • Token Expiry: For long-running applications, implement token refresh logic or handle access_token expiry gracefully.

3. Performance Tips

  • Caching: Cache user data fetched from OAuth providers to avoid repeated API calls:
    $response = $this->get('hwi_oauth.user.provider')->loadUserByOAuthUserResponse($response);
    // Cache $response->getAccessToken() and user data if needed
    
  • Lazy Loading: Use lazy-loading for user data to improve initial login speed.

4. Extension Points

  • Custom Providers: Extend the bundle by creating a custom resource owner type. See existing providers for examples.
  • Override Templates: Customize the login/connect templates by overriding the bundle’s templates in templates/HWIOAuthBundle/:
    {# templates/HWIOAuthBundle/Connect/connect.html.twig #}
    {% extends '@HWIOAuth/Connect/connect.html.twig' %}
    {% block title %}Custom OAuth Login{% endblock %}
    
  • HTTP Client Configuration: Adjust the HTTP client timeout for slow providers (e.g., FI-WARE):
    hwi_oauth:
        http_client:
            timeout: 15
    

5. Security Considerations

  • State Parameter: Always validate the state parameter in OAuth flows to prevent CSRF attacks.
  • Token Storage: Store access_token and refresh_token securely (e.g., encrypted in the database).
  • Provider-Specific Risks: Some providers (e.g., Twitter OAuth1.0a) have stricter security requirements. Follow their guidelines for client_id/client_secret handling.

6. Testing

  • Mock Providers: Use tools like OAuth Mock Server for testing without hitting real APIs.
  • Event Testing: Test the hwi_oauth.on.connect event to ensure post-login logic works as expected.

7. Upgrading

  • Version Compatibility: Check the upgrade guide for breaking changes between major versions (e.g., Symfony 6.x vs. 7.x).
  • Deprecated Features: Remove deprecated configurations (e.g., hwi_oauth.firewall_name in favor of firewall-specific settings).
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit