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) for authenticating to Google APIs and Google Cloud. Install via Composer and use with HTTP clients like Guzzle to authorize API calls.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require google/auth
    

    Add to composer.json under require:

    "google/auth": "^1.9"
    
  2. First Use Case: Fetch Application Default Credentials (ADC) for a Google API:

    use Google\Auth\ApplicationDefaultCredentials;
    
    $scopes = ['https://www.googleapis.com/auth/drive.readonly'];
    $middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
    
  3. Where to Look First:

    • Reference Docs
    • Google\Auth\ApplicationDefaultCredentials for ADC setup.
    • Google\Auth\CredentialsLoader for custom credential loading.

Implementation Patterns

Workflows

1. ADC Integration (Most Common)

// Laravel Service Provider (e.g., `GoogleAuthServiceProvider`)
public function register()
{
    $this->app->singleton('google.auth.middleware', function ($app) {
        $scopes = config('google.scopes');
        return ApplicationDefaultCredentials::getMiddleware($scopes);
    });
}

// HTTP Client (e.g., `app/Http/Clients/GoogleClient`)
public function __construct()
{
    $this->client = new Client([
        'handler' => HandlerStack::create()->push(
            $this->app->make('google.auth.middleware')
        ),
        'base_uri' => 'https://www.googleapis.com',
    ]);
}

2. Service Account Credentials (Non-ADC)

// Load from JSON file or env
$jsonKey = json_decode(file_get_contents(storage_path('app/google-credentials.json')), true);
$creds = new ServiceAccountCredentials(config('google.scopes'), $jsonKey);

// Cache tokens (e.g., using Laravel Cache)
$cache = new FileSystemCacheItemPool(storage_path('app/google-cache'));
$creds = new FetchAuthTokenCache($creds, [], $cache);

// Middleware
$middleware = new AuthTokenMiddleware($creds);

3. ID Token for Cloud Run/IAP

$middleware = ApplicationDefaultCredentials::getIdTokenMiddleware(
    config('google.iap.client_id')
);

4. JWT Verification (e.g., User Auth)

// Middleware for verifying Google ID tokens (e.g., in `app/Http/Middleware/VerifyGoogleToken`)
public function handle($request, Closure $next)
{
    $idToken = $request->bearerToken();
    $auth = new AccessToken();
    $auth->verify($idToken, [
        'certsLocation' => AccessToken::IAP_CERT_URL,
    ]);
    return $next($request);
}

Integration Tips

  1. Laravel Configuration: Add to config/google.php:

    return [
        'scopes' => [
            'https://www.googleapis.com/auth/drive',
            'https://www.googleapis.com/auth/calendar',
        ],
        'credentials_path' => storage_path('app/google-credentials.json'),
        'cache' => 'file', // 'memory', 'redis', or custom PSR-6 cache
    ];
    
  2. Caching Strategies:

    • Memory Cache: Use Google\Auth\Cache\MemoryCacheItemPool for short-lived tokens (e.g., testing).
    • File Cache: Use FileSystemCacheItemPool for persistence across requests.
    • Redis Cache: Integrate with Laravel's cache:
      $cache = new RedisCacheItemPool(
          Redis::connection('default')->getClient()
      );
      
  3. Quota Project (GCP Billing):

    $creds = ApplicationDefaultCredentials::getCredentials($scopes, [
        'quotaProjectId' => config('google.quota_project_id'),
    ]);
    
  4. Workload Identity Federation: Use ADC with GCP's Workload Identity to avoid hardcoding credentials:

    # Set env var in GCP (e.g., Cloud Run)
    GOOGLE_APPLICATION_CREDENTIALS=/var/run/secrets/google.iam.gserviceaccount.com
    

Gotchas and Tips

Pitfalls

  1. Credential Validation:

    • Never trust external credential sources. Validate JSON keys before use:
      $jsonKey = json_decode($rawJson, true);
      if (!isset($jsonKey['type'], $jsonKey['project_id'])) {
          throw new \InvalidArgumentException('Invalid credential format');
      }
      
  2. Token Expiry:

    • Tokens expire (typically 1 hour). Use caching to avoid frequent refreshes:
      $creds = new FetchAuthTokenCache($serviceAccountCreds, [], $cache);
      
    • Debugging: Check Google\Auth\Exception for token errors (e.g., InvalidCredentials).
  3. Scopes:

    • Minimize scopes: Request only necessary permissions (e.g., drive.readonly vs. drive).
    • Scope Mismatch: Errors like 403 Forbidden often stem from insufficient scopes.
  4. Environment Variables:

    • GOOGLE_APPLICATION_CREDENTIALS must point to a valid JSON key file (not a URL).
    • Testing: Use putenv() sparingly; prefer Laravel's .env:
      GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
      
  5. Guzzle Version:

    • Guzzle 6/7: Use getMiddleware().
    • Guzzle 5: Use getSubscriber() (deprecated in newer versions).

Debugging

  1. Enable Debug Logging:

    $creds = ApplicationDefaultCredentials::getCredentials($scopes, [
        'debug' => true,
    ]);
    

    Logs appear in storage/logs/laravel.log.

  2. Token Inspection:

    $token = $creds->fetchAuthToken();
    // Decode to check claims
    $decoded = (array) json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', $token)[1]))));
    
  3. Common Errors:

    • InvalidCredentials: Credential file corrupted or permissions issue. Fix: Regenerate JSON key in GCP Console.
    • TokenExpired: Token cache stale. Fix: Clear cache or reduce cache_ttl (default: 3600s).
    • ScopeViolation: Missing scope in request. Fix: Add scope to $scopes array.

Tips

  1. Laravel Facades: Create a facade for cleaner syntax:

    // app/Facades/GoogleAuth.php
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade;
    class GoogleAuth extends Facade {
        protected static function getFacadeAccessor() { return 'google.auth'; }
    }
    

    Usage:

    $middleware = GoogleAuth::middleware(['scope1', 'scope2']);
    
  2. Retry Logic: Handle 401 Unauthorized (token expired) with exponential backoff:

    try {
        $response = $client->get('...');
    } catch (Google\Auth\Exception $e) {
        if ($e->getCode() === 401) {
            $creds->refresh(); // Manually refresh
            retry();
        }
        throw $e;
    }
    
  3. Testing:

    • Use Google\Auth\TestOnly\MockCredentials for unit tests:
      $mockCreds = new MockCredentials(['access_token' => 'mock_token']);
      $middleware = new AuthTokenMiddleware($mockCreds);
      
    • Mock GOOGLE_APPLICATION_CREDENTIALS in .env.testing:
      GOOGLE_APPLICATION_CREDENTIALS=/dev/null
      
  4. Performance:

    • Cache TTL: Adjust cache_ttl (e.g., 300s for shorter-lived tokens).
    • Parallel Requests: Use Google\Auth\CredentialsLoader with a shared cache to avoid race conditions.
  5. Extension Points:

    • Custom Credentials: Extend Google\Auth\CredentialsInterface for OAuth2 flows.
    • Token Storage: Implement Google\Auth\Cache\CacheItemPoolInterface for custom storage (e.g., DynamoDB).
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport