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 Symfony Bundle Laravel Package

ekreative/oauth2-symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require ekreative/oauth2-symfony-bundle
    

    Register the bundle in config/bundles.php:

    Ekreative\OAuth2Bundle\OAuth2Bundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --tag=oauth2-config
    

    Update config/oauth2.php with your OAuth2 provider details (e.g., client ID, secret, authorization URL).

  3. First Use Case: Authentication Use the bundle’s Authenticator service to handle OAuth2 flows:

    use Ekreative\OAuth2Bundle\Service\Authenticator;
    
    class OAuthController extends Controller
    {
        public function redirectToProvider(Authenticator $authenticator)
        {
            return $authenticator->redirectToProvider();
        }
    
        public function handleProviderCallback(Authenticator $authenticator, Request $request)
        {
            $user = $authenticator->handleProviderCallback($request);
            // Store user in session or create a Laravel user.
        }
    }
    

Implementation Patterns

Workflows

  1. Authorization Code Flow (Recommended)

    • Redirect users to the provider:
      $authenticator->redirectToProvider('authorization_code');
      
    • Handle the callback:
      $user = $authenticator->handleProviderCallback($request);
      
    • Exchange code for tokens and fetch user data.
  2. Resource Owner Password Credentials Flow For trusted clients (e.g., mobile apps):

    $token = $authenticator->getAccessToken('password', [
        'username' => 'user@example.com',
        'password' => 'password',
    ]);
    
  3. Token Storage Use the TokenStorage service to persist/retieve tokens:

    $tokenStorage->store($token);
    $storedToken = $tokenStorage->getAccessToken();
    

Integration Tips

  • Laravel-Specific Adaptations Extend the bundle’s UserProvider to integrate with Laravel’s Auth system:

    use Ekreative\OAuth2Bundle\Security\User\UserProviderInterface;
    
    class LaravelUserProvider implements UserProviderInterface
    {
        public function loadUserByOAuthUserInfo($username, array $info)
        {
            return User::where('email', $username)->first();
        }
    }
    

    Register it in config/oauth2.php under user_provider.

  • Middleware for Protected Routes Use Symfony’s Firewall concept via Laravel’s middleware:

    class OAuthMiddleware
    {
        public function handle($request, Closure $next)
        {
            if (!$request->user()) {
                return redirect()->route('oauth.redirect');
            }
            return $next($request);
        }
    }
    
  • Custom Grant Types Extend the GrantType class to support non-standard flows:

    use Ekreative\OAuth2Bundle\GrantType\GrantTypeInterface;
    
    class CustomGrantType implements GrantTypeInterface
    {
        public function getName() { return 'custom'; }
        public function validate(array $params) { /* ... */ }
    }
    

    Register it in config/oauth2.php under grant_types.


Gotchas and Tips

Pitfalls

  1. In-Memory Token Storage The default in_memory driver is not persistent. Switch to orm for production:

    'driver' => 'orm',
    

    Ensure your AccessToken entity extends Ekreative\OAuth2Bundle\Model\AccessTokenEntity.

  2. CSRF Token Mismatch Symfony’s CSRF protection may conflict with OAuth2 redirects. Disable it for OAuth routes:

    // In routes/web.php
    Route::get('/oauth/callback', [OAuthController::class, 'handleCallback'])
        ->middleware('web')->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
    
  3. State Parameter Handling Always validate the state parameter in callbacks to prevent CSRF:

    $authenticator->setState($request->session()->get('oauth_state'));
    
  4. Provider-Specific Quirks Some providers (e.g., Google) require additional scopes or parameters. Check their docs and adjust config/oauth2.php:

    'providers' => [
        'google' => [
            'authorization_url' => 'https://accounts.google.com/o/oauth2/auth',
            'access_token_url' => 'https://oauth2.googleapis.com/token',
            'scope' => ['email', 'profile', 'https://www.googleapis.com/auth/userinfo.profile'],
        ],
    ],
    

Debugging

  • Enable Debug Mode Set 'debug' => true in config/oauth2.php to log OAuth2 requests/responses.

  • Token Validation Use the TokenValidator service to manually validate tokens:

    $validator = $container->get('oauth2.token_validator');
    $isValid = $validator->validate($token);
    
  • Common Errors

    • invalid_grant: Check credentials or token expiration.
    • redirect_uri_mismatch: Ensure the callback URL matches the registered one.
    • unsupported_grant_type: Verify the grant type is supported by the provider.

Extension Points

  1. Custom User Entity Extend the default UserEntity to add fields:

    use Ekreative\OAuth2Bundle\Model\UserEntity as BaseUserEntity;
    
    class CustomUserEntity extends BaseUserEntity
    {
        protected $avatarUrl;
        // Add getters/setters.
    }
    

    Update config/oauth2.php:

    'model' => [
        'user' => App\Entity\CustomUserEntity::class,
    ],
    
  2. Event Listeners Listen to OAuth2 events (e.g., oauth2.token_created):

    use Ekreative\OAuth2Bundle\Event\TokenEvent;
    
    $dispatcher->addListener('oauth2.token_created', function (TokenEvent $event) {
        // Log or process the token.
    });
    
  3. API Resource Server Use the bundle’s ResourceServer to validate access tokens for API requests:

    $resourceServer = $container->get('oauth2.resource_server');
    $isValid = $resourceServer->validateRequest($request);
    
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