PHPackages                             davicente/oauth2-client - 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. davicente/oauth2-client

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

davicente/oauth2-client
=======================

OAuth 2.0 Client Library

2.3.1(8y ago)08.9k1MITPHPPHP &gt;=5.6.0

Since Mar 25Pushed 8y ago1 watchersCompare

[ Source](https://github.com/davicente/oauth2-client)[ Packagist](https://packagist.org/packages/davicente/oauth2-client)[ RSS](/packages/davicente-oauth2-client/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (8)Versions (36)Used By (1)

OAuth 2.0 Client
================

[](#oauth-20-client)

This package makes it simple to integrate your application with [OAuth 2.0](http://oauth.net/2/) service providers. Since 2.3.0 version (first version in this repo) Guzzle version used is v5.3. Several updates were made in order to support this old version of Guzzle.

[![Gitter Chat](https://camo.githubusercontent.com/d5966c6ec9d0765b4cb7fcfed04fc777c6b436830f91288061d83b02cbf1ba5d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6769747465722d6a6f696e5f636861742d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://gitter.im/thephpleague/oauth2-client)[![Source Code](https://camo.githubusercontent.com/fd8b77c9b3cdd42601b6158798ec6581e63e16e94af557ef5832d654962d6468/687474703a2f2f696d672e736869656c64732e696f2f62616467652f736f757263652d7468657068706c65616775652f6f61757468322d2d636c69656e742d626c75652e7376673f7374796c653d666c61742d737175617265)](https://github.com/thephpleague/oauth2-client)[![Latest Version](https://camo.githubusercontent.com/039e8e503af2d6fe76c16e2cd4801c4ac0997d31f00835015fc4a32682532074/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7468657068706c65616775652f6f61757468322d636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://github.com/thephpleague/oauth2-client/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/thephpleague/oauth2-client/blob/master/LICENSE)[![Build Status](https://camo.githubusercontent.com/c5447a51f6d48c0cd5ff75dad7ade3d0ce8c7834a14baf67457de60254494537/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7468657068706c65616775652f6f61757468322d636c69656e742f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/thephpleague/oauth2-client)[![HHVM Status](https://camo.githubusercontent.com/7451004bf5cc955aba25797853d7396e2333df5f01b015813e15c700b241f962/68747470733a2f2f696d672e736869656c64732e696f2f6868766d2f6c65616775652f6f61757468322d636c69656e742e7376673f7374796c653d666c61742d737175617265)](http://hhvm.h4cc.de/package/league/oauth2-client)[![Scrutinizer](https://camo.githubusercontent.com/b1dc185a3f31ea1939a80e9b73e4717da327625cffb82771798305b55a6b57ab/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f7468657068706c65616775652f6f61757468322d636c69656e742f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/thephpleague/oauth2-client/)[![Coverage Status](https://camo.githubusercontent.com/25a761fb6e5410b446e6399966f21cbced21c834d922687644e0832afadf5f6c/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f7468657068706c65616775652f6f61757468322d636c69656e742f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://coveralls.io/r/thephpleague/oauth2-client?branch=master)[![Total Downloads](https://camo.githubusercontent.com/8ec673bbfdbeca8600bb35d811212d486eac7502a2939180ae70290d708db203/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6c65616775652f6f61757468322d636c69656e742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/league/oauth2-client)

---

We are all used to seeing those "Connect with Facebook/Google/etc." buttons around the internet, and social network integration is an important feature of most web applications these days. Many of these sites use an authentication and authorization standard called OAuth 2.0 ([RFC 6749](http://tools.ietf.org/html/rfc6749)).

This OAuth 2.0 client library will work with any OAuth provider that conforms to the OAuth 2.0 standard. Out-of-the-box, we provide a `GenericProvider` that may be used to connect to any service provider that uses [Bearer tokens](http://tools.ietf.org/html/rfc6750) (see example below).

Many service providers provide additional functionality above and beyond the OAuth 2.0 standard. For this reason, this library may be easily extended and wrapped to support this additional behavior. We provide links to [all known provider clients extending this library](docs/providers/thirdparty.md) (i.e. Facebook, GitHub, Google, Instagram, LinkedIn, etc.). If your provider isn't in the list, feel free to add it.

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), [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md), and [PSR-7](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-7-http-message.md). If you notice compliance oversights, please send a patch via pull request. If you're interesting in contributing to this library, please take a look at our [contributing guidelines](CONTRIBUTING.md).

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

[](#requirements)

The following versions of PHP are supported.

- PHP 5.6
- PHP 7.0
- PHP 7.1
- HHVM

Providers
---------

[](#providers)

A list of official PHP League providers, as well as third-party providers, may be found in the [providers list README](docs/providers/thirdparty.md).

To build your own provider, please refer to the [provider guide README](README.PROVIDER-GUIDE.md).

Usage
-----

[](#usage)

**In most cases, you'll want to use a specific provider client library rather than this base library.**

Take a look at [providers list README](docs/providers/thirdparty.md) to see a list of provider client libraries.

If using Composer to require a specific provider client library, you **do not need to also require this library**. Composer will handle the dependencies for you.

### Authorization Code Grant

[](#authorization-code-grant)

The following example uses the out-of-the-box `GenericProvider` provided by this library. If you're looking for a specific provider (i.e. Facebook, Google, GitHub, etc.), take a look at our [list of provider client libraries](docs/providers/thirdparty.md). **HINT: You're probably looking for a specific provider.**

The authorization code grant type is the most common grant type used when authenticating users with a third-party service. This grant type utilizes a client (this library), a server (the service provider), and a resource owner (the user with credentials to a protected—or owned—resource) to request access to resources owned by the user. This is often referred to as *3-legged OAuth*, since there are three parties involved.

The following example illustrates this using [Brent Shaffer's](https://github.com/bshaffer) demo OAuth 2.0 application named **Lock'd In**. When running this code, you will be redirected to Lock'd In, where you'll be prompted to authorize the client to make requests to a resource on your behalf.

Now, you don't really have an account on Lock'd In, but for the sake of this example, imagine that you are already logged in on Lock'd In when you are redirected there.

```
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'demoapp',    // The client ID assigned to you by the provider
    'clientSecret'            => 'demopass',   // The client password assigned to you by the provider
    'redirectUri'             => 'http://example.com/your-redirect-url/',
    'urlAuthorize'            => 'http://brentertainment.com/oauth2/lockdin/authorize',
    'urlAccessToken'          => 'http://brentertainment.com/oauth2/lockdin/token',
    'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl();

    // Get the state generated for you and store it to the session.
    $_SESSION['oauth2state'] = $provider->getState();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {

    if (isset($_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
    }

    exit('Invalid state');

} else {

    try {

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

        // We have an access token, which we may use in authenticated
        // requests against the service provider's API.
        echo 'Access Token: ' . $accessToken->getToken() . "";
        echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "";
        echo 'Expired in: ' . $accessToken->getExpires() . "";
        echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);

        var_export($resourceOwner->toArray());

        // The provider provides a way to get an authenticated API request for
        // the service, using the access token; it returns an object conforming
        // to Psr\Http\Message\RequestInterface.
        $request = $provider->getAuthenticatedRequest(
            'GET',
            'http://brentertainment.com/oauth2/lockdin/resource',
            $accessToken
        );

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

        // Failed to get the access token or user details.
        exit($e->getMessage());

    }

}
```

### Refreshing a Token

[](#refreshing-a-token)

Once your application is authorized, you can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse this refresh token from your data store to request a refresh.

*This example uses [Brent Shaffer's](https://github.com/bshaffer) demo OAuth 2.0 application named **Lock'd In**. See authorization code example above, for more details.*

```
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'demoapp',    // The client ID assigned to you by the provider
    'clientSecret'            => 'demopass',   // The client password assigned to you by the provider
    'redirectUri'             => 'http://example.com/your-redirect-url/',
    'urlAuthorize'            => 'http://brentertainment.com/oauth2/lockdin/authorize',
    'urlAccessToken'          => 'http://brentertainment.com/oauth2/lockdin/token',
    'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);

$existingAccessToken = getAccessTokenFromYourDataStore();

if ($existingAccessToken->hasExpired()) {
    $newAccessToken = $provider->getAccessToken('refresh_token', [
        'refresh_token' => $existingAccessToken->getRefreshToken()
    ]);

    // Purge old access token and store new access token to your data store.
}
```

### Resource Owner Password Credentials Grant

[](#resource-owner-password-credentials-grant)

Some service providers allow you to skip the authorization code step to exchange a user's credentials (username and password) for an access token. This is referred to as the "resource owner password credentials" grant type.

According to [section 1.3.3](http://tools.ietf.org/html/rfc6749#section-1.3.3) of the OAuth 2.0 standard (emphasis added):

> The credentials **should only be used when there is a high degree of trust**between the resource owner and the client (e.g., the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available (such as an authorization code).

**We do not advise using this grant type if the service provider supports the authorization code grant type (see above), as this reinforces the [password anti-pattern](https://agentile.com/the-password-anti-pattern) by allowing users to think it's okay to trust third-party applications with their usernames and passwords.**

That said, there are use-cases where the resource owner password credentials grant is acceptable and useful. Here's an example using it with [Brent Shaffer's](https://github.com/bshaffer) demo OAuth 2.0 application named **Lock'd In**. See authorization code example above, for more details about the Lock'd In demo application.

```
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'demoapp',    // The client ID assigned to you by the provider
    'clientSecret'            => 'demopass',   // The client password assigned to you by the provider
    'redirectUri'             => 'http://example.com/your-redirect-url/',
    'urlAuthorize'            => 'http://brentertainment.com/oauth2/lockdin/authorize',
    'urlAccessToken'          => 'http://brentertainment.com/oauth2/lockdin/token',
    'urlResourceOwnerDetails' => 'http://brentertainment.com/oauth2/lockdin/resource'
]);

try {

    // Try to get an access token using the resource owner password credentials grant.
    $accessToken = $provider->getAccessToken('password', [
        'username' => 'demouser',
        'password' => 'testpass'
    ]);

} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

    // Failed to get the access token
    exit($e->getMessage());

}
```

### Client Credentials Grant

[](#client-credentials-grant)

When your application is acting on its own behalf to access resources it controls/owns in a service provider, it may use the client credentials grant type. This is best used when the credentials for your application are stored privately and never exposed (e.g. through the web browser, etc.) to end-users. This grant type functions similarly to the resource owner password credentials grant type, but it does not request a user's username or password. It uses only the client ID and secret issued to your client by the service provider.

Unlike earlier examples, the following does not work against a functioning demo service provider. It is provided for the sake of example only.

```
// Note: the GenericProvider requires the `urlAuthorize` option, even though
// it's not used in the OAuth 2.0 client credentials grant type.

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'XXXXXX',    // The client ID assigned to you by the provider
    'clientSecret'            => 'XXXXXX',    // The client password assigned to you by the provider
    'redirectUri'             => 'http://my.example.com/your-redirect-url/',
    'urlAuthorize'            => 'http://service.example.com/authorize',
    'urlAccessToken'          => 'http://service.example.com/token',
    'urlResourceOwnerDetails' => 'http://service.example.com/resource'
]);

try {

    // Try to get an access token using the client credentials grant.
    $accessToken = $provider->getAccessToken('client_credentials');

} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

    // Failed to get the access token
    exit($e->getMessage());

}
```

### Using a proxy

[](#using-a-proxy)

It is possible to use a proxy to debug HTTP calls made to a provider. All you need to do is set the `proxy` and `verify` options when creating your Provider instance. Make sure you enable SSL proxying in your proxy.

```
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'XXXXXX',    // The client ID assigned to you by the provider
    'clientSecret'            => 'XXXXXX',    // The client password assigned to you by the provider
    'redirectUri'             => 'http://my.example.com/your-redirect-url/',
    'urlAuthorize'            => 'http://service.example.com/authorize',
    'urlAccessToken'          => 'http://service.example.com/token',
    'urlResourceOwnerDetails' => 'http://service.example.com/resource',
    'proxy'                   => '192.168.0.1:8888',
    'verify'                  => false
]);
```

Install
-------

[](#install)

Via Composer

```
$ composer require league/oauth2-client
```

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

[](#contributing)

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

License
-------

[](#license)

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

###  Health Score

35

—

LowBetter than 81% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community22

Small or concentrated contributor base

Maturity70

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

Recently: every ~33 days

Total

35

Last Release

3211d ago

Major Versions

0.12.1 → 1.0.0-alpha12015-06-25

1.4.2 → 2.0.02017-01-13

PHP version history (4 changes)0.1PHP &gt;=5.3.0

0.4.0PHP &gt;=5.4.0

1.0.0-alpha1PHP &gt;=5.5.0

2.0.0PHP &gt;=5.6.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/919fd3b2e75a952f03e3a9bc6edecf386c6643ee355b5df9862d23798cba6861?d=identicon)[davicente](/maintainers/davicente)

---

Top Contributors

[![ramsey](https://avatars.githubusercontent.com/u/42941?v=4)](https://github.com/ramsey "ramsey (288 commits)")[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (125 commits)")[![alexbilbie](https://avatars.githubusercontent.com/u/77991?v=4)](https://github.com/alexbilbie "alexbilbie (58 commits)")[![rtheunissen](https://avatars.githubusercontent.com/u/809191?v=4)](https://github.com/rtheunissen "rtheunissen (38 commits)")[![stevenmaguire](https://avatars.githubusercontent.com/u/1851973?v=4)](https://github.com/stevenmaguire "stevenmaguire (27 commits)")[![philsturgeon](https://avatars.githubusercontent.com/u/67381?v=4)](https://github.com/philsturgeon "philsturgeon (16 commits)")[![jildertmiedema](https://avatars.githubusercontent.com/u/3383186?v=4)](https://github.com/jildertmiedema "jildertmiedema (15 commits)")[![bencorlett](https://avatars.githubusercontent.com/u/181919?v=4)](https://github.com/bencorlett "bencorlett (11 commits)")[![TomHAnderson](https://avatars.githubusercontent.com/u/493920?v=4)](https://github.com/TomHAnderson "TomHAnderson (8 commits)")[![jamesmills](https://avatars.githubusercontent.com/u/557096?v=4)](https://github.com/jamesmills "jamesmills (8 commits)")[![tpavlek](https://avatars.githubusercontent.com/u/782576?v=4)](https://github.com/tpavlek "tpavlek (7 commits)")[![adam-paterson](https://avatars.githubusercontent.com/u/1008727?v=4)](https://github.com/adam-paterson "adam-paterson (7 commits)")[![msurguy](https://avatars.githubusercontent.com/u/585833?v=4)](https://github.com/msurguy "msurguy (6 commits)")[![jasonvarga](https://avatars.githubusercontent.com/u/105211?v=4)](https://github.com/jasonvarga "jasonvarga (5 commits)")[![aripringle](https://avatars.githubusercontent.com/u/1278449?v=4)](https://github.com/aripringle "aripringle (5 commits)")[![SammyK](https://avatars.githubusercontent.com/u/578780?v=4)](https://github.com/SammyK "SammyK (5 commits)")[![jeremykendall](https://avatars.githubusercontent.com/u/288613?v=4)](https://github.com/jeremykendall "jeremykendall (5 commits)")[![hajekj](https://avatars.githubusercontent.com/u/8337913?v=4)](https://github.com/hajekj "hajekj (4 commits)")[![rakeev](https://avatars.githubusercontent.com/u/1861570?v=4)](https://github.com/rakeev "rakeev (4 commits)")[![zot24](https://avatars.githubusercontent.com/u/678498?v=4)](https://github.com/zot24 "zot24 (3 commits)")

---

Tags

AuthenticationSSOidentityoauthoauth2authorizationidpsingle sign on

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/davicente-oauth2-client/health.svg)

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

###  Alternatives

[league/oauth2-client

OAuth 2.0 Client Library

3.8k115.1M1.0k](/packages/league-oauth2-client)

PHPackages © 2026

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