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

Auth Laravel Package

google/auth

Official Google Auth library for PHP. Implements OAuth 2.0 and Application Default Credentials (ADC) to authenticate and authorize requests to Google APIs. Designed for Composer installs and use across local, server, and Google Cloud environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require google/auth
    
  2. Basic ADC Setup (for local/dev environments):

    export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account.json"
    

    Or in Laravel's .env:

    GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account.json
    
  3. First API Call (e.g., Google Drive):

    use Google\Auth\ApplicationDefaultCredentials;
    use GuzzleHttp\Client;
    
    $scopes = ['https://www.googleapis.com/auth/drive.readonly'];
    $client = new Client([
        'base_uri' => 'https://www.googleapis.com',
        'auth' => ApplicationDefaultCredentials::getMiddleware($scopes)
    ]);
    
    $response = $client->get('drive/v2/files');
    return $response->getBody()->getContents();
    

Where to Look First

  • Laravel Service Provider: Create a provider to initialize the client once (e.g., GoogleAuthServiceProvider).
  • Config File: Store scopes, cache settings, and credential paths in config/google.php.
  • Facade Pattern: Wrap the client in a facade (e.g., GoogleAuth) for cleaner syntax.

First Use Case

Fetching Google Sheets Data:

$scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
$client = new Client([
    'base_uri' => 'https://sheets.googleapis.com/v4',
    'auth' => ApplicationDefaultCredentials::getMiddleware($scopes)
]);
$response = $client->get('/spreadsheets/{spreadsheetId}');

Implementation Patterns

Workflows

  1. Service Provider Initialization:

    // app/Providers/GoogleAuthServiceProvider.php
    public function register()
    {
        $this->app->singleton('google.auth.client', function ($app) {
            $scopes = config('google.scopes');
            return new Client([
                'base_uri' => config('google.base_uri'),
                'auth' => ApplicationDefaultCredentials::getMiddleware($scopes)
            ]);
        });
    }
    
  2. Facade for Clean Usage:

    // app/Facades/GoogleAuth.php
    public static function getClient()
    {
        return app('google.auth.client');
    }
    
    // Usage:
    $response = GoogleAuth::getClient()->get('drive/v2/files');
    
  3. Scoped Clients:

    // For different APIs with distinct scopes
    $driveClient = new Client([
        'auth' => ApplicationDefaultCredentials::getMiddleware(['https://www.googleapis.com/auth/drive'])
    ]);
    
    $sheetsClient = new Client([
        'auth' => ApplicationDefaultCredentials::getMiddleware(['https://www.googleapis.com/auth/spreadsheets'])
    ]);
    
  4. Caching Tokens:

    use Google\Auth\Cache\FileSystemCacheItemPool;
    
    $cache = new FileSystemCacheItemPool(storage_path('app/google_cache'));
    $credentials = ApplicationDefaultCredentials::getCredentials(
        ['https://www.googleapis.com/auth/drive'],
        cache: $cache
    );
    
  5. Impersonation (for GSuite admins):

    use Google\Auth\ImpersonatedServiceAccountCredentials;
    
    $credentials = new ImpersonatedServiceAccountCredentials(
        ['https://www.googleapis.com/auth/admin.directory.user'],
        $serviceAccountJson,
        'admin@example.com' // User to impersonate
    );
    

Integration Tips

  • Laravel HTTP Client: Use Laravel's HTTP client with middleware:
    $client = Http::withOptions([
        'auth' => ApplicationDefaultCredentials::getMiddleware($scopes)
    ]);
    
  • Queue Jobs: Initialize the client in a job's handle() method to avoid global state.
  • Testing: Mock ApplicationDefaultCredentials in tests:
    $mockCredentials = Mockery::mock('Google\Auth\CredentialsInterface');
    $mockCredentials->shouldReceive('fetchAuthToken')->andReturn('mock_token');
    ApplicationDefaultCredentials::setCredentials($mockCredentials);
    

Gotchas and Tips

Pitfalls

  1. Scope Mismatches:

    • Ensure scopes match the API's requirements (e.g., drive.readonly vs. drive).
    • Fix: Double-check Google's API docs for exact scopes.
  2. Credential Path Issues:

    • GOOGLE_APPLICATION_CREDENTIALS must point to a valid JSON key file.
    • Fix: Use absolute paths and validate the file exists:
      if (!file_exists($path)) {
          throw new RuntimeException("Credentials file not found at {$path}");
      }
      
  3. Token Expiry:

    • Tokens expire after 1 hour (default). Retries may fail silently.
    • Fix: Enable caching or handle Google\Auth\Exception:
      try {
          $response = $client->get('...');
      } catch (Google\Auth\Exception $e) {
          // Retry with fresh credentials
      }
      
  4. Guzzle 6+ Compatibility:

    • The library drops Guzzle 5 support. Use HandlerStack for Guzzle 6+:
      $stack = HandlerStack::create();
      $stack->push(ApplicationDefaultCredentials::getMiddleware($scopes));
      
  5. Workload Identity Federation:

Debugging

  1. Enable Debug Logging:

    putenv('GOOGLE_AUTH_LOG_LEVEL=debug');
    

    Logs appear in stderr or Laravel's log channel.

  2. Token Inspection:

    $credentials = ApplicationDefaultCredentials::getCredentials($scopes);
    $token = $credentials->fetchAuthToken(); // Inspect the raw token
    
  3. Common Exceptions:

    • Google\Auth\Exception: Catch for auth failures (e.g., invalid credentials).
    • Google\Auth\CredentialsException: Invalid JSON key format.

Tips

  1. Environment-Specific Credentials: Use Laravel's .env for different environments:

    GOOGLE_APPLICATION_CREDENTIALS_LOCAL=/path/to/local.json
    GOOGLE_APPLICATION_CREDENTIALS_PROD=/path/to/prod.json
    

    Load dynamically:

    $path = env('GOOGLE_APPLICATION_CREDENTIALS_' . config('app.env'));
    
  2. Cache Invalidation: Clear cache when rotating service account keys:

    $cache->clear(); // For FileSystemCacheItemPool
    
  3. Async Support: Use ApplicationDefaultCredentials::getAsyncMiddleware() for async handlers (e.g., ReactPHP):

    $loop = React\EventLoop\Factory::create();
    $connector = new React\Http\Message\Client($loop);
    $stack = HandlerStack::create();
    $stack->push(ApplicationDefaultCredentials::getAsyncMiddleware($scopes));
    
  4. Proxy-Authorization: For IAP or Cloud Run, use getProxyIdTokenMiddleware to avoid Authorization header conflicts.

  5. Service Account Impersonation: Store impersonated users in config and rotate them periodically for security:

    config(['google.impersonated_user' => 'admin@example.com']);
    
  6. Validation: Validate JSON keys before use (e.g., check client_email and private_key fields):

    $json = json_decode(file_get_contents($path), true);
    if (empty($json['client_email']) || empty($json['private_key'])) {
        throw new InvalidArgumentException('Invalid JSON key');
    }
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui