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.
Install the package:
composer require google/auth
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'))
);
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();
AppServiceProvider@boot():
$this->app->singleton('google.credentials', function () {
return ApplicationDefaultCredentials::getCredentials(['scope']);
});
GoogleAuthFacade) to wrap common operations.// 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();
}
// 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()
);
// 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'
]);
// 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);
}
}
// 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);
}
// 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());
}
Environment Variable Overrides:
.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'));
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:
chmod 600 storage/app/google-credentials.json
Missing Scopes:
403 Forbidden, verify scopes are:
https://www.googleapis.com/auth/...).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'
]);
Cache Invalidation:
FetchAuthTokenCache with a short TTL (e.g., 55 minutes) to avoid race conditions:
$cache = new FetchAuthTokenCache($credentials, [
'ttl' => 3300 // 55 minutes
]);
Cache::remember() for token storage:
$token = Cache::remember('google.auth.token', 3300, function () use ($credentials) {
return $credentials->fetchAuthToken();
});
PSR-6 Compliance:
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();
AWS/Azure Setup:
workloadidentity.user role.https://accounts.google.com).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',
],
IAP-Specific Certificates:
$auth->verify($idToken, [
'certsLocation' => AccessToken::IAP_CERT_URL
]);
azp claim (authorized party) that must match your IAP app’s client ID.Custom Claims:
email_verified):
$auth->verify($
How can I help you explore Laravel packages today?