Weave 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 provides OAuth 2.0 authorization and authentication for Google and Cloud APIs. It implements Application Default Credentials (ADC) to help applications obtain credentials and securely call APIs, with easy Composer installation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel

  1. Install the package:

    composer require google/auth
    
  2. Configure credentials (choose one method):

    • Environment variable (recommended for Laravel):

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

      Store your JSON key file in storage/app/google-credentials.json and reference it in .env:

      GOOGLE_APPLICATION_CREDENTIALS=storage/app/google-credentials.json
      
    • Direct initialization (for testing/non-production):

      use Google\Auth\ServiceAccountCredentials;
      $credentials = new ServiceAccountCredentials(
          ['https://www.googleapis.com/auth/drive.readonly'],
          file_get_contents(storage_path('app/google-credentials.json'))
      );
      
  3. First API call (using Guzzle):

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

Key Laravel Integration Points

  • Service Provider: Register credentials in AppServiceProvider@boot():
    $this->app->singleton('google.credentials', function () {
        return ApplicationDefaultCredentials::getCredentials(['scope']);
    });
    
  • Facade: Create a facade (GoogleAuthFacade) to wrap common operations.

Implementation Patterns

1. Service Account Workflow (Common for GCP)

// In a service class (e.g., GoogleDriveService.php)
public function listFiles()
{
    $credentials = ApplicationDefaultCredentials::getCredentials([
        'https://www.googleapis.com/auth/drive.metadata.readonly'
    ]);

    $client = new Client([
        'handler' => HandlerStack::create(
            new AuthTokenMiddleware($credentials)
        ),
        'base_uri' => 'https://www.googleapis.com'
    ]);

    return $client->get('drive/v3/files')->getBody();
}

2. Caching Tokens (Performance Optimization)

// Use Laravel's cache (PSR-6 compliant)
use Google\Auth\Cache\FileSystemCacheItemPool;
use Illuminate\Support\Facades\Cache;

$cache = new FileSystemCacheItemPool(storage_path('framework/cache/google'));
$credentials = ApplicationDefaultCredentials::getCredentials(
    ['scope'],
    cache: $cache
    // OR use Laravel's cache directly:
    // cache: Cache::store('file')->getHandler()
);

3. Workload Identity Federation (AWS/Azure)

// For federated identities (e.g., AWS IAM roles)
$credentials = ApplicationDefaultCredentials::getCredentials([
    'https://www.googleapis.com/auth/cloud-platform'
], [
    'quotaProject' => 'your-gcp-project-id',
    'subjectTokenType' => 'urn:ietf:params:oauth:token-type:jwt',
    'tokenUrl' => 'https://oauth2.googleapis.com/token'
]);

4. ID Token Verification (User Auth)

// In a controller (e.g., GoogleAuthController.php)
public function verifyToken(Request $request)
{
    $auth = new AccessToken();
    try {
        $auth->verify($request->id_token, [
            'issuer' => 'https://accounts.google.com',
            'audience' => config('services.google.client_id')
        ]);
        return response()->json(['valid' => true]);
    } catch (InvalidArgumentException $e) {
        return response()->json(['error' => $e->getMessage()], 401);
    }
}

5. Middleware for API Routes

// In app/Http/Middleware/GoogleAuthMiddleware.php
public function handle($request, Closure $next)
{
    $scopes = ['https://www.googleapis.com/auth/your-api'];
    $middleware = ApplicationDefaultCredentials::getMiddleware($scopes);

    $stack = HandlerStack::create($middleware);
    $client = new Client(['handler' => $stack]);

    // Attach to Laravel's HTTP client if using Guzzle
    $request->setClient($client);

    return $next($request);
}

6. Testing with Mock Credentials

// In a test case
public function testGoogleAuth()
{
    $mockCredentials = $this->createMock(ServiceAccountCredentials::class);
    $mockCredentials->method('fetchAuthToken')->willReturn('mock-token');

    $middleware = new AuthTokenMiddleware($mockCredentials);
    $stack = HandlerStack::create($middleware);

    $client = new Client(['handler' => $stack]);
    $response = $client->get('https://example.com/api');

    $this->assertEquals(200, $response->getStatusCode());
}

Gotchas and Tips

1. Credential Loading Pitfalls

  • Environment Variable Overrides:

    • Laravel’s .env files are loaded after GOOGLE_APPLICATION_CREDENTIALS is set. If you set it in bootstrap/app.php, ensure it’s before Laravel’s environment loading:
      putenv('GOOGLE_APPLICATION_CREDENTIALS=' . storage_path('app/google-credentials.json'));
      
    • Tip: Use env() in AppServiceProvider@register() to dynamically set the path:
      $this->app->singleton('google.credentials.path', function () {
          return env('GOOGLE_CREDENTIALS_PATH', storage_path('app/google-credentials.json'));
      });
      
  • File Permissions:

    • Ensure the JSON key file is readable by the web server:
      chmod 600 storage/app/google-credentials.json
      

2. Scope Management

  • Missing Scopes:

    • If you get 403 Forbidden, verify scopes are:
      1. Correctly formatted (e.g., https://www.googleapis.com/auth/...).
      2. Enabled in Google Cloud Console.
      3. Included in the Service Account’s "Roles" (e.g., "Storage Admin" for drive scopes).
  • Tip: Use Google\Auth\ApplicationDefaultCredentials::getCredentials() with an array of scopes:

    $credentials = ApplicationDefaultCredentials::getCredentials([
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/cloud-platform'
    ]);
    

3. Caching Quirks

  • Cache Invalidation:

    • Tokens expire after 1 hour (default). Use FetchAuthTokenCache with a short TTL (e.g., 55 minutes) to avoid race conditions:
      $cache = new FetchAuthTokenCache($credentials, [
          'ttl' => 3300 // 55 minutes
      ]);
      
    • Laravel Tip: Use Cache::remember() for token storage:
      $token = Cache::remember('google.auth.token', 3300, function () use ($credentials) {
          return $credentials->fetchAuthToken();
      });
      
  • PSR-6 Compliance:

    • Laravel’s Cache facade is not PSR-6 compliant. Use Symfony\Component\Cache\Adapter\FilesystemAdapter or Google\Auth\Cache\FileSystemCacheItemPool:
      use Symfony\Component\Cache\Adapter\FilesystemAdapter;
      $cache = new FilesystemAdapter();
      

4. Workload Identity Federation

  • AWS/Azure Setup:

    • Ensure the Google Service Account has the workloadidentity.user role.
    • The external provider (AWS IAM/Azure AD) must trust Google’s OIDC issuer (https://accounts.google.com).
    • Debugging: Check logs for InvalidSubjectToken errors (common if the subject claim doesn’t match the federated identity).
  • Laravel Tip: Store federated credentials in config/google.php:

    'federation' => [
        'quota_project' => env('GOOGLE_QUOTA_PROJECT'),
        'subject_token_type' => 'urn:ietf:params:oauth:token-type:jwt',
    ],
    

5. ID Token Verification

  • IAP-Specific Certificates:

    • For Identity-Aware Proxy (IAP), use:
      $auth->verify($idToken, [
          'certsLocation' => AccessToken::IAP_CERT_URL
      ]);
      
    • Gotcha: IAP tokens have a azp claim (authorized party) that must match your IAP app’s client ID.
  • Custom Claims:

    • To verify custom claims (e.g., email_verified):
      $auth->verify($
      
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.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log