PHPackages                             wsj-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. wsj-google/auth

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

wsj-google/auth
===============

Google Auth Library for PHP

01PHP

Since Dec 27Pushed 3y agoCompare

[ Source](https://github.com/Wen-sijun/google-auth)[ Packagist](https://packagist.org/packages/wsj-google/auth)[ RSS](/packages/wsj-google-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

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

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

 Homepage Reference Docs Authors [Tim Emiola](mailto:temiola@google.com) [Stanley Cheung](mailto:stanleycheung@google.com) [Brent Shaffer](mailto:betterbrent@google.com) CopyrightCopyright © 2015 Google, Inc. LicenseApache 2.0Description
-----------

[](#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](https://developers.google.com/accounts/docs/application-default-credentials) for PHP.

The Application Default Credentials provide a simple way to get authorization credentials for use in calling Google APIs.

They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Compute Engine.

#### Download your Service Account Credentials JSON file

[](#download-your-service-account-credentials-json-file)

To use `Application Default Credentials`, You first need to download a set of JSON credentials for your project. Go to **APIs &amp; Services** &gt; **Credentials** in the [Google Developers Console](https://console.developers.google.com) and select **Service account** from the **Add credentials** dropdown.

> This file is your *only copy* of these credentials. It should never be committed with your source code, and should be stored securely.

Once downloaded, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable.

```
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
```

> PHP's `putenv` function is just one way to set an environment variable. Consider using `.htaccess` or apache configuration files as well.

#### 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
$creds = CredentialsLoader::makeCredentials($scopes, $jsonKey);

// 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());
```

#### 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
]);
```

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

15

—

LowBetter than 3% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity1

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity23

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/e3e957aaa0dd4c234fccf0a95639b71e2ecab42c5b0805ed3ac1860dfe81979d?d=identicon)[Wen-sijun](/maintainers/Wen-sijun)

---

Top Contributors

[![bshaffer](https://avatars.githubusercontent.com/u/103941?v=4)](https://github.com/bshaffer "bshaffer (161 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)")[![jdpedrie](https://avatars.githubusercontent.com/u/89034?v=4)](https://github.com/jdpedrie "jdpedrie (19 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)")[![renovate-bot](https://avatars.githubusercontent.com/u/25180681?v=4)](https://github.com/renovate-bot "renovate-bot (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)")[![release-please[bot]](https://avatars.githubusercontent.com/in/40688?v=4)](https://github.com/release-please[bot] "release-please[bot] (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)")[![michaelbausor](https://avatars.githubusercontent.com/u/14846209?v=4)](https://github.com/michaelbausor "michaelbausor (3 commits)")[![JustinBeckwith](https://avatars.githubusercontent.com/u/534619?v=4)](https://github.com/JustinBeckwith "JustinBeckwith (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)")[![ZhouyihaiDing](https://avatars.githubusercontent.com/u/28968539?v=4)](https://github.com/ZhouyihaiDing "ZhouyihaiDing (1 commits)")[![gabihodoroaga](https://avatars.githubusercontent.com/u/5672653?v=4)](https://github.com/gabihodoroaga "gabihodoroaga (1 commits)")[![imdhemy](https://avatars.githubusercontent.com/u/22864831?v=4)](https://github.com/imdhemy "imdhemy (1 commits)")[![KasperFranz](https://avatars.githubusercontent.com/u/191405?v=4)](https://github.com/KasperFranz "KasperFranz (1 commits)")[![mortonfox](https://avatars.githubusercontent.com/u/495892?v=4)](https://github.com/mortonfox "mortonfox (1 commits)")

### Embed Badge

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

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

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

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