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.
Installation:
composer require google/auth
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
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();
GoogleAuthServiceProvider).config/google.php.GoogleAuth) for cleaner syntax.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}');
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)
]);
});
}
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');
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'])
]);
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
);
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
);
$client = Http::withOptions([
'auth' => ApplicationDefaultCredentials::getMiddleware($scopes)
]);
handle() method to avoid global state.ApplicationDefaultCredentials in tests:
$mockCredentials = Mockery::mock('Google\Auth\CredentialsInterface');
$mockCredentials->shouldReceive('fetchAuthToken')->andReturn('mock_token');
ApplicationDefaultCredentials::setCredentials($mockCredentials);
Scope Mismatches:
drive.readonly vs. drive).Credential Path Issues:
GOOGLE_APPLICATION_CREDENTIALS must point to a valid JSON key file.if (!file_exists($path)) {
throw new RuntimeException("Credentials file not found at {$path}");
}
Token Expiry:
Google\Auth\Exception:
try {
$response = $client->get('...');
} catch (Google\Auth\Exception $e) {
// Retry with fresh credentials
}
Guzzle 6+ Compatibility:
HandlerStack for Guzzle 6+:
$stack = HandlerStack::create();
$stack->push(ApplicationDefaultCredentials::getMiddleware($scopes));
Workload Identity Federation:
Enable Debug Logging:
putenv('GOOGLE_AUTH_LOG_LEVEL=debug');
Logs appear in stderr or Laravel's log channel.
Token Inspection:
$credentials = ApplicationDefaultCredentials::getCredentials($scopes);
$token = $credentials->fetchAuthToken(); // Inspect the raw token
Common Exceptions:
Google\Auth\Exception: Catch for auth failures (e.g., invalid credentials).Google\Auth\CredentialsException: Invalid JSON key format.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'));
Cache Invalidation: Clear cache when rotating service account keys:
$cache->clear(); // For FileSystemCacheItemPool
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));
Proxy-Authorization:
For IAP or Cloud Run, use getProxyIdTokenMiddleware to avoid Authorization header conflicts.
Service Account Impersonation: Store impersonated users in config and rotate them periodically for security:
config(['google.impersonated_user' => 'admin@example.com']);
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');
}
How can I help you explore Laravel packages today?