PHPackages                             google/auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. google/auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

google/auth
===========

Google Auth Library for PHP

v1.50.1(2mo ago)1.4k272.7M—2.7%194[16 issues](https://github.com/googleapis/google-auth-library-php/issues)[5 PRs](https://github.com/googleapis/google-auth-library-php/pulls)20Apache-2.0PHPPHP ^8.1CI failing

Since Sep 16Pushed 2mo ago65 watchersCompare

[ Source](https://github.com/googleapis/google-auth-library-php)[ Packagist](https://packagist.org/packages/google/auth)[ Docs](https://github.com/google/google-auth-library-php)[ RSS](/packages/google-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (32)Versions (121)Used By (20)

Google Auth Library for PHP
===========================

[](#google-auth-library-for-php)

[Reference Docs](https://cloud.google.com/php/docs/reference/auth/latest)

Description
-----------

[](#description)

This is Google's officially supported PHP client library for using OAuth 2.0 authorization and authentication with Google APIs.

### Installing via Composer

[](#installing-via-composer)

The recommended way to install the google auth library is through [Composer](http://getcomposer.org).

```
# Install Composer
curl -sS https://getcomposer.org/installer | php
```

Next, run the Composer command to install the latest stable version:

```
composer.phar require google/auth
```

Application Default Credentials
-------------------------------

[](#application-default-credentials)

This library provides an implementation of [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) for PHP.

Application Default Credentials provides a simple way to get authorization credentials for use in calling Google APIs, and is the recommended approach to authorize calls to Cloud APIs.

**Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud Platform, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to [Validate credential configurations from external sources](https://cloud.google.com/docs/authentication/external/externally-sourced-credentials).

### Set up ADC

[](#set-up-adc)

To use ADC, you must set it up by providing credentials. How you set up ADC depends on the environment where your code is running, and whether you are running code in a test or production environment.

For more information, see [Set up Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).

### Enable the API you want to use

[](#enable-the-api-you-want-to-use)

Before making your API call, you must be sure the API you're calling has been enabled. Go to **APIs &amp; Auth** &gt; **APIs** in the [Google Developers Console](https://console.developers.google.com) and enable the APIs you'd like to call. For the example below, you must enable the `Drive API`.

### Call the APIs

[](#call-the-apis)

As long as you update the environment variable below to point to *your* JSON credentials file, the following code should output a list of your Drive files.

```
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'base_uri' => 'https://www.googleapis.com',
  'auth' => 'google_auth'  // authorize all requests
]);

// make the request
$response = $client->get('drive/v2/files');

// show the result!
print_r((string) $response->getBody());
```

##### Guzzle 5 Compatibility

[](#guzzle-5-compatibility)

If you are using [Guzzle 5](http://docs.guzzlephp.org/en/5.3), replace the `create middleware` and `create the HTTP Client` steps with the following:

```
// create the HTTP client
$client = new Client([
  'base_url' => 'https://www.googleapis.com',
  'auth' => 'google_auth'  // authorize all requests
]);

// create subscriber
$subscriber = ApplicationDefaultCredentials::getSubscriber($scopes);
$client->getEmitter()->attach($subscriber);
```

#### Call using an ID Token

[](#call-using-an-id-token)

If your application is running behind Cloud Run, or using Cloud Identity-Aware Proxy (IAP), you will need to fetch an ID token to access your application. For this, use the static method `getIdTokenMiddleware` on `ApplicationDefaultCredentials`.

```
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// Provide the ID token audience. This can be a Client ID associated with an IAP application,
// Or the URL associated with a CloudRun App
//    $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';
//    $targetAudience = 'https://service-1234-uc.a.run.app';
$targetAudience = 'YOUR_ID_TOKEN_AUDIENCE';

// create middleware
$middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($targetAudience);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'auth' => 'google_auth',
  // Cloud Run, IAP, or custom resource URL
  'base_uri' => 'https://YOUR_PROTECTED_RESOURCE',
]);

// make the request
$response = $client->get('/');

// show the result!
print_r((string) $response->getBody());
```

For invoking Cloud Run services, your service account will need the [`Cloud Run Invoker`](https://cloud.google.com/run/docs/authenticating/service-to-service)IAM permission.

For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID used when you set up your protected resource as the target audience. See how to [secure your IAP app with signed headers](https://cloud.google.com/iap/docs/signed-headers-howto).

#### Call using a specific JSON key

[](#call-using-a-specific-json-key)

If you want to use a specific JSON key instead of using `GOOGLE_APPLICATION_CREDENTIALS` environment variable, you can do this:

```
use Google\Auth\CredentialsLoader;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// Define the Google Application Credentials array
$jsonKey = ['key' => 'value'];

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

// Load credentials from JSON containing service account credentials.
$creds = new ServiceAccountCredentials($scopes, $jsonKey),

// For other credentials types, create those classes explicitly using the
// "type" field in the JSON key, for example:
$creds = match ($jsonKey['type']) {
    'service_account' => new ServiceAccountCredentials($scope, $jsonKey),
    'authorized_user' => new UserRefreshCredentials($scope, $jsonKey),
    default => throw new InvalidArgumentException('This application only supports service account and user account credentials'),
};

// optional caching
$creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);

// create middleware
$middleware = new AuthTokenMiddleware($creds);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'base_uri' => 'https://www.googleapis.com',
  'auth' => 'google_auth'  // authorize all requests
]);

// make the request
$response = $client->get('drive/v2/files');

// show the result!
print_r((string) $response->getBody());
```

#### Call using Proxy-Authorization Header

[](#call-using-proxy-authorization-header)

If your application is behind a proxy such as [Google Cloud IAP](https://cloud.google.com/iap/docs/authentication-howto#authenticating_from_proxy-authorization_header), and your application occupies the `Authorization` request header, you can include the ID token in a `Proxy-Authorization: Bearer`header instead. If a valid ID token is found in a `Proxy-Authorization` header, IAP authorizes the request with it. After authorizing the request, IAP passes the Authorization header to your application without processing the content. For this, use the static method `getProxyIdTokenMiddleware` on `ApplicationDefaultCredentials`.

```
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// Provide the ID token audience. This can be a Client ID associated with an IAP application
//    $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';
$targetAudience = 'YOUR_ID_TOKEN_AUDIENCE';

// create middleware
$middleware = ApplicationDefaultCredentials::getProxyIdTokenMiddleware($targetAudience);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'auth' => ['username', 'pass'], // auth option handled by your application
  'proxy_auth' => 'google_auth',
]);

// make the request
$response = $client->get('/');

// show the result!
print_r((string) $response->getBody());
```

#### External credentials (Workload identity federation)

[](#external-credentials-workload-identity-federation)

Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).

Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.

Follow the detailed instructions on how to [Configure Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds).

#### Verifying JWTs

[](#verifying-jwts)

If you are [using Google ID tokens to authenticate users](https://developers.google.com/identity/sign-in/web/backend-auth), use the `Google\Auth\AccessToken` class to verify the ID token:

```
use Google\Auth\AccessToken;

$auth = new AccessToken();
$auth->verify($idToken);
```

If your app is running behind [Google Identity-Aware Proxy](https://cloud.google.com/iap/docs/signed-headers-howto)(IAP), you can verify the ID token coming from the IAP server by pointing to the appropriate certificate URL for IAP. This is because IAP signs the ID tokens with a different key than the Google Identity service:

```
use Google\Auth\AccessToken;

$auth = new AccessToken();
$auth->verify($idToken, [
  'certsLocation' => AccessToken::IAP_CERT_URL
]);
```

Caching
-------

[](#caching)

Caching is enabled by passing a PSR-6 `CacheItemPoolInterface`instance to the constructor when instantiating the credentials.

We offer some caching classes out of the box under the `Google\Auth\Cache` namespace.

```
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Cache\MemoryCacheItemPool;

// Cache Instance
$memoryCache = new MemoryCacheItemPool;

// Get the credentials
// From here, the credentials will cache the access token
$middleware = ApplicationDefaultCredentials::getCredentials($scope, cache: $memoryCache);
```

### FileSystemCacheItemPool Cache

[](#filesystemcacheitempool-cache)

The `FileSystemCacheItemPool` class is a `PSR-6` compliant cache that stores its serialized objects on disk, caching data between processes and making it possible to use data between different requests.

```
use Google\Auth\Cache\FileSystemCacheItemPool;
use Google\Auth\ApplicationDefaultCredentials;

// Create a Cache pool instance
$cache = new FileSystemCacheItemPool(__DIR__ . '/cache');

// Pass your Cache to the Auth Library
$credentials = ApplicationDefaultCredentials::getCredentials($scope, cache: $cache);

// This token will be cached and be able to be used for the next request
$token = $credentials->fetchAuthToken();
```

### Integrating with a third party cache

[](#integrating-with-a-third-party-cache)

You can use a third party that follows the `PSR-6` interface of your choice.

```
// run "composer require symfony/cache"
use Google\Auth\ApplicationDefaultCredentials;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

// Create the cache instance
$filesystemCache = new FilesystemAdapter();

// Create Get the credentials
$credentials = ApplicationDefaultCredentials::getCredentials($targetAudience, cache: $filesystemCache);
```

License
-------

[](#license)

This library is licensed under Apache 2.0. Full license text is available in [COPYING](https://github.com/google/google-auth-library-php/tree/main/COPYING).

Contributing
------------

[](#contributing)

See [CONTRIBUTING](https://github.com/google/google-auth-library-php/tree/main/.github/CONTRIBUTING.md).

Support
-------

[](#support)

Please [report bugs at the project on Github](https://github.com/google/google-auth-library-php/issues). Don't hesitate to [ask questions](http://stackoverflow.com/questions/tagged/google-auth-library-php)about the client or APIs on [StackOverflow](http://stackoverflow.com).

###  Health Score

81

—

ExcellentBetter than 100% of packages

Maintenance88

Actively maintained with recent releases

Popularity81

Widely adopted with strong download metrics

Community54

Growing community involvement

Maturity89

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~40 days

Recently: every ~45 days

Total

96

Last Release

61d ago

Major Versions

v0.11.1 → v1.02017-06-13

v1.18.0 → v2.x-dev2021-12-06

PHP version history (7 changes)v0.1-alphaPHP &gt;=5.4

v2.x-devPHP &gt;=7.1

v1.19.0PHP &gt;=5.6

v1.20.0PHP ^7.1||^8.0

v1.27.0PHP ^7.4||^8.0

v1.38.0PHP ^8.0

v1.43.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/a8713415b20b4be4cec8f8b22741e3cd05f76eee9e38de1de5bf32727349b7c5?d=identicon)[bshaffer](/maintainers/bshaffer)

![](https://www.gravatar.com/avatar/3901206952845568d7557a60855b097f6d1bafaa7a24020cfcf5bb8de74f9d28?d=identicon)[google-cloud](/maintainers/google-cloud)

---

Top Contributors

[![bshaffer](https://avatars.githubusercontent.com/u/103941?v=4)](https://github.com/bshaffer "bshaffer (228 commits)")[![tbetbetbe](https://avatars.githubusercontent.com/u/9272342?v=4)](https://github.com/tbetbetbe "tbetbetbe (45 commits)")[![stanley-cheung](https://avatars.githubusercontent.com/u/11674202?v=4)](https://github.com/stanley-cheung "stanley-cheung (39 commits)")[![release-please[bot]](https://avatars.githubusercontent.com/in/40688?v=4)](https://github.com/release-please[bot] "release-please[bot] (38 commits)")[![jdpedrie](https://avatars.githubusercontent.com/u/89034?v=4)](https://github.com/jdpedrie "jdpedrie (19 commits)")[![renovate-bot](https://avatars.githubusercontent.com/u/25180681?v=4)](https://github.com/renovate-bot "renovate-bot (16 commits)")[![murgatroid99](https://avatars.githubusercontent.com/u/961599?v=4)](https://github.com/murgatroid99 "murgatroid99 (15 commits)")[![dwsupplee](https://avatars.githubusercontent.com/u/2079879?v=4)](https://github.com/dwsupplee "dwsupplee (9 commits)")[![Hectorhammett](https://avatars.githubusercontent.com/u/9062626?v=4)](https://github.com/Hectorhammett "Hectorhammett (7 commits)")[![yash30201](https://avatars.githubusercontent.com/u/54198301?v=4)](https://github.com/yash30201 "yash30201 (7 commits)")[![vishwarajanand](https://avatars.githubusercontent.com/u/7369612?v=4)](https://github.com/vishwarajanand "vishwarajanand (6 commits)")[![jeromegamez](https://avatars.githubusercontent.com/u/67554?v=4)](https://github.com/jeromegamez "jeromegamez (5 commits)")[![cedricziel](https://avatars.githubusercontent.com/u/418970?v=4)](https://github.com/cedricziel "cedricziel (4 commits)")[![michaelbausor](https://avatars.githubusercontent.com/u/14846209?v=4)](https://github.com/michaelbausor "michaelbausor (3 commits)")[![silvolu](https://avatars.githubusercontent.com/u/596919?v=4)](https://github.com/silvolu "silvolu (3 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (3 commits)")[![PaolaRuby](https://avatars.githubusercontent.com/u/79208489?v=4)](https://github.com/PaolaRuby "PaolaRuby (2 commits)")[![google-cloud-policy-bot[bot]](https://avatars.githubusercontent.com/in/105725?v=4)](https://github.com/google-cloud-policy-bot[bot] "google-cloud-policy-bot[bot] (2 commits)")[![JustinBeckwith](https://avatars.githubusercontent.com/u/534619?v=4)](https://github.com/JustinBeckwith "JustinBeckwith (2 commits)")[![yfuruyama](https://avatars.githubusercontent.com/u/1595215?v=4)](https://github.com/yfuruyama "yfuruyama (1 commits)")

---

Tags

googleAuthenticationoauth2

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/google-auth/health.svg)

```
[![Health](https://phpackages.com/badges/google-auth/health.svg)](https://phpackages.com/packages/google-auth)
```

###  Alternatives

[kreait/firebase-php

Firebase Admin SDK

2.4k39.7M72](/packages/kreait-firebase-php)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[shopify/shopify-api

Shopify API Library for PHP

4634.8M16](/packages/shopify-shopify-api)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[kinde-oss/kinde-auth-php

Kinde PHP SDK for authentication

2369.5k3](/packages/kinde-oss-kinde-auth-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
