PHPackages                             league/oauth2-google - 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. league/oauth2-google

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

league/oauth2-google
====================

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

5.0.0(1mo ago)42121.2M—8.7%77[5 issues](https://github.com/thephpleague/oauth2-google/issues)20MITPHPPHP ^8.0CI failing

Since Mar 22Pushed 1mo ago14 watchersCompare

[ Source](https://github.com/thephpleague/oauth2-google)[ Packagist](https://packagist.org/packages/league/oauth2-google)[ RSS](/packages/league-oauth2-google/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (22)Used By (20)

Google Provider for OAuth 2.0 Client
====================================

[](#google-provider-for-oauth-20-client)

[![Build Status](https://camo.githubusercontent.com/25d4dca79de73d0686e64e5b8d6b30f9779de273143c2a73fe34273a13646f1d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468657068706c65616775652f6f61757468322d676f6f676c652f63692e796d6c3f6272616e63683d6d61696e)](https://github.com/thephpleague/oauth2-google/actions/workflows/ci.yml)[![Code Coverage](https://camo.githubusercontent.com/c84edd2891027dc6ba71830c4ebbdf926dd124ddd10615d6efd70bd6f320f2df/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f67682f7468657068706c65616775652f6f61757468322d676f6f676c65)](https://app.codecov.io/gh/thephpleague/oauth2-google)[![License](https://camo.githubusercontent.com/d3af1fbb3f0361080706520e3204de2bcb992cb3b99de608926b8dea01cd9727/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6c65616775652f6f61757468322d676f6f676c65)](https://github.com/thephpleague/oauth2-google/blob/main/LICENSE)[![Latest Stable Version](https://camo.githubusercontent.com/626837a7f96c267dbbda9957ba8321d3392bb3e945d1cab661095b7a1fb5eb51/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6c65616775652f6f61757468322d676f6f676c65)](https://packagist.org/packages/league/oauth2-google)

This package provides Google OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

This package is compliant with [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md), [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) and [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md). If you notice compliance oversights, please send a patch via pull request.

Requirements
------------

[](#requirements)

The following versions of PHP are supported. Support for older PHP versions is available in version 4.2 (and older) of this library.

- PHP 8.0
- PHP 8.1
- PHP 8.2
- PHP 8.3
- PHP 8.4
- PHP 8.5

This package uses [OpenID Connect](https://developers.google.com/identity/protocols/OpenIDConnect) to authenticate users with Google accounts.

To use this package, it will be necessary to have a Google client ID and client secret. These are referred to as `{google-client-id}` and `{google-client-secret}`in the documentation.

Please follow the [Google instructions](https://developers.google.com/identity/protocols/OpenIDConnect#registeringyourapp) to create the required credentials.

Installation
------------

[](#installation)

To install, use composer:

```
composer require league/oauth2-google
```

Usage
-----

[](#usage)

### Authorization Code Flow

[](#authorization-code-flow)

```
require __DIR__ . '/vendor/autoload.php';

use League\OAuth2\Client\Provider\Google;

session_start(); // Remove if session.auto_start=1 in php.ini

$provider = new Google([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'hostedDomain' => 'example.com', // optional; used to restrict access to users on your G Suite/Google Apps for Business accounts
]);

if (!empty($_GET['error'])) {

    // Got an error, probably user denied access
    exit('Got error: ' . htmlspecialchars($_GET['error'], ENT_QUOTES, 'UTF-8'));

} elseif (empty($_GET['code'])) {

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;

} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    // State is invalid, possible CSRF attack in progress
    unset($_SESSION['oauth2state']);
    exit('Invalid state');

} else {

    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);

    // Optional: Now you have a token you can look up a users profile data
    try {

        // We got an access token, let's now get the owner details
        $ownerDetails = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $ownerDetails->getFirstName());

    } catch (Exception $e) {

        // Failed to get user details
        exit('Something went wrong: ' . $e->getMessage());

    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();

    // Use this to get a new access token if the old one expires
    echo $token->getRefreshToken();

    // Unix timestamp at which the access token expires
    echo $token->getExpires();
}
```

#### Available Options

[](#available-options)

The `Google` provider has the following [options](https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters):

- `accessType` to use online or offline access
- `hostedDomain` to authenticate G Suite users
- `prompt` to modify the prompt that the user will see
- `scopes` to request access to additional user information

#### Accessing Token JWT

[](#accessing-token-jwt)

Google provides a [JSON Web Token](https://jwt.io/) (JWT) with all access tokens. This token [contains basic information](https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo) about the authenticated user. The JWT can be accessed from the `id_token` value of the access token:

```
/** @var League\OAuth2\Client\Token\AccessToken $token */
$values = $token->getValues();

/** @var string */
$jwt = $values['id_token'];
```

Parsing the JWT will require a [JWT parser](https://packagist.org/search/?q=jwt). Refer to parser documentation for instructions.

### Refreshing a Token

[](#refreshing-a-token)

Refresh tokens are only provided to applications which request offline access. You can specify offline access by setting the `accessType` option in your provider:

```
use League\OAuth2\Client\Provider\Google;

$provider = new Google([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'accessType'   => 'offline',
]);
```

It is important to note that the refresh token is only returned on the first request after this it will be `null`. You should securely store the refresh token when it is returned:

```
$token = $provider->getAccessToken('authorization_code', [
    'code' => $code
]);

// persist the token in a database
$refreshToken = $token->getRefreshToken();
```

If you ever need to get a new refresh token you can request one by forcing the consent prompt:

```
$authUrl = $provider->getAuthorizationUrl(['prompt' => 'consent', 'access_type' => 'offline']);
```

Now you have everything you need to refresh an access token using a refresh token:

```
use League\OAuth2\Client\Provider\Google;
use League\OAuth2\Client\Grant\RefreshToken;

$provider = new Google([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
]);

$grant = new RefreshToken();
$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);
```

Scopes
------

[](#scopes)

Additional [scopes](https://developers.google.com/identity/protocols/googlescopes) can be set by using the `scope` parameter when generating the authorization URL:

```
$authorizationUrl = $provider->getAuthorizationUrl([
    'scope' => [
        'scope-url-here'
    ],
]);
```

Testing
-------

[](#testing)

Tests can be run with:

```
composer test
```

Style checks can be run with:

```
composer check
```

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

[](#contributing)

Please see [CONTRIBUTING](https://github.com/thephpleague/oauth2-google/blob/main/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Woody Gilk](https://github.com/shadowhand)
- [All Contributors](https://github.com/thephpleague/oauth2-google/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-google/blob/main/LICENSE) for more information.

###  Health Score

73

—

ExcellentBetter than 100% of packages

Maintenance89

Actively maintained with recent releases

Popularity69

Solid adoption and visibility

Community48

Growing community involvement

Maturity77

Established project with proven stability

 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 ~201 days

Recently: every ~461 days

Total

21

Last Release

56d ago

Major Versions

v0.2.0 → 1.0.0-beta12015-08-03

1.0.1 → 2.0.02017-01-24

2.2.0 → 3.0.02018-12-23

3.0.4 → 4.0.02021-03-04

4.2.0 → 5.0.02026-03-23

PHP version history (4 changes)v0.1.0PHP &gt;=5.4.0

4.0.0PHP &gt;=7.3

4.0.1PHP ^7.3 || ^8.0

5.0.0PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/38203?v=4)[Woody Gilk](/maintainers/shadowhand)[@shadowhand](https://github.com/shadowhand)

---

Top Contributors

[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (112 commits)")[![ramsey](https://avatars.githubusercontent.com/u/42941?v=4)](https://github.com/ramsey "ramsey (51 commits)")[![alexbilbie](https://avatars.githubusercontent.com/u/77991?v=4)](https://github.com/alexbilbie "alexbilbie (29 commits)")[![Yozhef](https://avatars.githubusercontent.com/u/8971757?v=4)](https://github.com/Yozhef "Yozhef (12 commits)")[![philsturgeon](https://avatars.githubusercontent.com/u/67381?v=4)](https://github.com/philsturgeon "philsturgeon (10 commits)")[![TomHAnderson](https://avatars.githubusercontent.com/u/493920?v=4)](https://github.com/TomHAnderson "TomHAnderson (6 commits)")[![aripringle](https://avatars.githubusercontent.com/u/1278449?v=4)](https://github.com/aripringle "aripringle (5 commits)")[![jildertmiedema](https://avatars.githubusercontent.com/u/3383186?v=4)](https://github.com/jildertmiedema "jildertmiedema (4 commits)")[![bencorlett](https://avatars.githubusercontent.com/u/181919?v=4)](https://github.com/bencorlett "bencorlett (4 commits)")[![jamesmills](https://avatars.githubusercontent.com/u/557096?v=4)](https://github.com/jamesmills "jamesmills (4 commits)")[![pradtke](https://avatars.githubusercontent.com/u/932934?v=4)](https://github.com/pradtke "pradtke (4 commits)")[![rakeev](https://avatars.githubusercontent.com/u/1861570?v=4)](https://github.com/rakeev "rakeev (4 commits)")[![tpavlek](https://avatars.githubusercontent.com/u/782576?v=4)](https://github.com/tpavlek "tpavlek (4 commits)")[![msurguy](https://avatars.githubusercontent.com/u/585833?v=4)](https://github.com/msurguy "msurguy (3 commits)")[![garak](https://avatars.githubusercontent.com/u/179866?v=4)](https://github.com/garak "garak (3 commits)")[![GrahamCampbell](https://avatars.githubusercontent.com/u/2829600?v=4)](https://github.com/GrahamCampbell "GrahamCampbell (3 commits)")[![dhrrgn](https://avatars.githubusercontent.com/u/149921?v=4)](https://github.com/dhrrgn "dhrrgn (2 commits)")[![Zaksh](https://avatars.githubusercontent.com/u/357642?v=4)](https://github.com/Zaksh "Zaksh (2 commits)")[![jaylinski](https://avatars.githubusercontent.com/u/1668766?v=4)](https://github.com/jaylinski "jaylinski (2 commits)")[![jamesgraham](https://avatars.githubusercontent.com/u/934542?v=4)](https://github.com/jamesgraham "jamesgraham (2 commits)")

---

Tags

googleoauth2oauth2-providerphpclientgoogleAuthenticationoauthoauth2authorization

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

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

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

###  Alternatives

[cakedc/oauth2-cognito

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

18597.7k](/packages/cakedc-oauth2-cognito)

PHPackages © 2026

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