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

Laravel Oauth Laravel Package

mckenziearts/laravel-oauth

Laravel package providing OAuth authentication integration, enabling your app to act as an OAuth client for third-party providers. Includes configuration helpers and middleware to streamline login, token handling, and user retrieval in Laravel projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require mckenziearts/laravel-oauth
    
  2. Publish Configuration:
    php artisan vendor:publish --provider="LaravelOAuth\LaravelOAuthServiceProvider"
    
    • This generates config/oauth.php with default provider keys (Facebook, Twitter, Google, etc.).
  3. Configure Providers:
    • Edit config/oauth.php and add your OAuth app credentials (e.g., client_id, client_secret, redirect).
    • Example for Google:
      'google' => [
          'client_id' => env('GOOGLE_CLIENT_ID'),
          'client_secret' => env('GOOGLE_CLIENT_SECRET'),
          'redirect' => env('GOOGLE_REDIRECT_URI'),
      ],
      
  4. Add to .env:
    GOOGLE_CLIENT_ID=your_client_id
    GOOGLE_CLIENT_SECRET=your_client_secret
    GOOGLE_REDIRECT_URI=http://your-app.com/auth/google/callback
    
  5. Register Service Provider: Ensure LaravelOAuth\LaravelOAuthServiceProvider::class is in config/app.php under providers.

First Use Case: Redirect to Google OAuth

  1. Route Definition (routes/web.php):
    Route::get('/auth/google', 'Auth\LoginController@redirectToGoogle');
    Route::get('/auth/google/callback', 'Auth\LoginController@handleGoogleCallback');
    
  2. Controller Logic (Auth/LoginController.php):
    use LaravelOAuth\LaravelOAuth;
    
    public function redirectToGoogle()
    {
        return LaravelOAuth::driver('google')->redirect();
    }
    
    public function handleGoogleCallback()
    {
        try {
            $user = LaravelOAuth::driver('google')->getUser();
            // Handle user data (e.g., create/update user in DB)
            return redirect()->route('dashboard');
        } catch (\Exception $e) {
            return redirect()->route('login')->with('error', 'Google auth failed: ' . $e->getMessage());
        }
    }
    
  3. View Button (resources/views/auth/login.blade.php):
    <a href="{{ route('auth.google') }}" class="btn btn-google">
        Login with Google
    </a>
    

Implementation Patterns

Core Workflows

1. Provider-Specific Authentication

  • Pattern: Use the LaravelOAuth facade to abstract provider logic.
  • Example:
    // Redirect to provider
    return LaravelOAuth::driver('facebook')->redirect();
    
    // Handle callback
    $user = LaravelOAuth::driver('facebook')->getUser();
    
  • Tip: Store provider-specific user data in a users table with a provider_id column.

2. User Data Handling

  • Pattern: Normalize user data from providers into a consistent format.
  • Example:
    $userData = [
        'name' => $user->name,
        'email' => $user->email,
        'provider_id' => $user->id,
        'provider' => 'google',
    ];
    User::updateOrCreate(
        ['email' => $userData['email']],
        $userData
    );
    
  • Tip: Use Laravel’s updateOrCreate to avoid duplicate users.

3. Middleware for Authenticated Users

  • Pattern: Protect routes with auth middleware or custom logic.
  • Example:
    Route::middleware(['auth:social'])->group(function () {
        Route::get('/dashboard', 'DashboardController@index');
    });
    
  • Custom Middleware (app/Http/Middleware/AuthenticateSocial.php):
    public function handle($request, Closure $next)
    {
        if (!auth()->check() || !auth()->user()->provider) {
            return redirect()->route('login');
        }
        return $next($request);
    }
    

4. Revoking Access

  • Pattern: Use provider-specific revoke methods.
  • Example:
    LaravelOAuth::driver('google')->revoke();
    

5. Custom Providers

  • Pattern: Extend the package for unsupported providers (e.g., GitLab, Instagram).
  • Example:
    // Register a custom driver in config/oauth.php
    'gitlab' => [
        'driver' => \LaravelOAuth\Providers\GitLab::class,
        'client_id' => env('GITLAB_CLIENT_ID'),
        'client_secret' => env('GITLAB_CLIENT_SECRET'),
        'redirect' => env('GITLAB_REDIRECT_URI'),
    ],
    

Integration Tips

  • Laravel Mix: If using Webpack Mix, ensure webpack.mix.js is configured to compile assets (e.g., OAuth buttons).
  • Testing: Use Laravel’s HttpTests to mock OAuth callbacks:
    public function testGoogleAuth()
    {
        $response = $this->get('/auth/google');
        $response->assertRedirect('https://accounts.google.com/o/oauth2/auth');
    
        // Mock callback response
        $this->actingAs(User::find(1))
             ->get('/auth/google/callback')
             ->assertRedirect('/dashboard');
    }
    
  • Logging: Log OAuth errors for debugging:
    try {
        $user = LaravelOAuth::driver('twitter')->getUser();
    } catch (\Exception $e) {
        \Log::error('Twitter OAuth failed: ' . $e->getMessage());
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Laravel Facades:

    • Issue: The package may use older facades (e.g., Auth::user() instead of auth()->user()).
    • Fix: Update calls to use Laravel 6+ syntax or patch the package.
  2. Missing Provider Support:

    • Issue: Some providers (e.g., Instagram) require manual setup.
    • Fix: Check the GitHub issues for workarounds or extend the package.
  3. State Management:

    • Issue: OAuth state tokens may cause CSRF issues if not handled.
    • Fix: Ensure your routes include the state parameter:
      Route::get('/auth/google', function () {
          return LaravelOAuth::driver('google')->redirect(['state' => 'secure_state']);
      });
      
  4. Configuration Caching:

    • Issue: After publishing config, run:
      php artisan config:clear
      php artisan cache:clear
      
    • Fix: Clear caches if OAuth redirects fail silently.
  5. Provider-Specific Quirks:

    • Twitter: Requires additional permissions (e.g., tweet.read).
    • LinkedIn: May need r_liteprofile scope.
    • Fix: Refer to provider-specific docs.
  6. Laravel 6+ Compatibility:

    • Issue: Some methods may conflict with newer Laravel versions.
    • Fix: Test thoroughly and use a wrapper if needed:
      class OAuthWrapper {
          public static function getUser($provider) {
              return LaravelOAuth::driver($provider)->getUser();
          }
      }
      

Debugging Tips

  1. Enable Debugging:
    • Set APP_DEBUG=true in .env to see detailed errors.
  2. Check Provider Responses:
    • Log the raw response from providers:
      $response = LaravelOAuth::driver('facebook')->getUser();
      \Log::debug('Facebook response:', [$response->toArray()]);
      
  3. Validate Redirect URIs:
    • Ensure redirect URLs in config/oauth.php match your app’s domain (including http/https).
  4. Test in Isolation:
    • Use a separate .env file for OAuth credentials to avoid leaks.

Extension Points

  1. Custom User Model:
    • Bind a custom user model to the package:
      LaravelOAuth::extend('google', function ($app) {
          return new \LaravelOAuth\Providers\Google($app, new \App\Models\User());
      });
      
  2. Add Scopes:
    • Extend providers to request additional scopes:
      LaravelOAuth::driver('github')->scopes(['repo', 'user']);
      
  3. Webhook Handling:
    • For providers with webhooks (e.g., GitHub), create a route:
      Route::post('/github/webhook', 'WebhookController@handleGitHubWebhook');
      
  4. Rate Limiting:
    • Add middleware to limit OAuth requests:
      Route::middleware(['throttle:60,1'])->group(function () {
          Route::get('/auth/google', 'AuthController@redirectToGoogle
      
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.
monarobase/country-list
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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
testo/output-teamcity
testo/bridge-symfony