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

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

lucinda/oauth2-client
=====================

API abstracting communication with OAuth2 providers (eg: facebook) for PHP applications based on IETF standards

v3.1.2(3y ago)023.7k13MITPHPPHP ^8.1

Since Nov 7Pushed 3y ago1 watchersCompare

[ Source](https://github.com/aherne/oauth2client)[ Packagist](https://packagist.org/packages/lucinda/oauth2-client)[ Docs](http://www.lucinda-framework.com/oauth2-client)[ RSS](/packages/lucinda-oauth2-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (46)Used By (3)

OAuth2 Client API
=================

[](#oauth2-client-api)

Table of contents:

- [About](#about)
- [Registration](#registration)
- [Configuration](#configuration)
- [Execution](#execution)
    - [Initialization](#initialization)
    - [Querying Provider](#querying-provider)
- [Installation](#installation)
- [Unit Tests](#unit-tests)

About
-----

[](#about)

This API, came by the idea of building a shared driver based on [IETF specs](https://tools.ietf.org/html/rfc6749) that abstracts communication with popular OAuth2 providers so you're no longer forced to work their bloated PHP clients.

[![diagram](https://camo.githubusercontent.com/b39e981fbbabce7894c89ec0897c19050ab3d5bdc63cba3c1521f76ed97a532c/68747470733a2f2f7777772e6c7563696e64612d6672616d65776f726b2e636f6d2f6f61757468322d636c69656e742d6170692e737667)](https://camo.githubusercontent.com/b39e981fbbabce7894c89ec0897c19050ab3d5bdc63cba3c1521f76ed97a532c/68747470733a2f2f7777772e6c7563696e64612d6672616d65776f726b2e636f6d2f6f61757468322d636c69656e742d6170692e737667)

It has now become a fully matured time-tested API able to hide almost entirely communication complexity with these providers by this series of steps:

- **[registration](#registration)**: registering your site on oauth2 providers in order to be able to query them later on
- **[configuration](#configuration)**: setting up an XML file where one or more loggers are set for each development environment
- **[initialization](#initialization)**: creating a [Lucinda\\OAuth2\\Wrapper](https://github.com/aherne/oauth2client/blob/master/src/Wrapper.php) instance based on above XML and current development environment then calling *getDriver()* method based on requested page
- **[querying provider](#querying-provider)**: use shared driver [Lucinda\\OAuth2\\Driver](https://github.com/aherne/oauth2client/blob/master/src/Driver.php) instance resulting from method above to query respective provider

API is fully PSR-4 compliant, only requiring PHP 8.1+ interpreter, [Lucinda URL Requester](https://github.com/aherne/requester) and SimpleXML extension. To quickly see how it works, check:

- **[installation](#installation)**: describes how to install API on your computer, in light of steps above
- **[unit tests](#unit-tests)**: API has 100% Unit Test coverage, using [UnitTest API](https://github.com/aherne/unit-testing) instead of PHPUnit for greater flexibility
- **[example](#example)**: shows a example of API functionality based on unit test for [Lucinda\\OAuth2\\Wrapper](https://github.com/aherne/oauth2client/blob/master/src/Wrapper.php)

Registration
------------

[](#registration)

OAuth2 requires your site (the client) to be available on world-wide-web in order to communicate with provider (the server). To do so your site must be registered on provider's site, same way as a user would! Registration endpoints for supported providers are:

- Facebook:
- Google:
- Instagram:
- LinkedIn:
- GitHub:
- VK:
- Yahoo:
- Yandex:

Once you land there you will be asked on registration to fill a form in which you will need to supply:

- **redirect\_uri**: (always) complete link to your site where OAUTH2 vendor should redirect authorization code to
- **scopes**: (sometimes) rights specific to vendor your site require on each site client's account
- **application\_name**: (only by GitHub) unique name that identifies your site against others

Once registered, your site will get:

- **client\_id**: public id that identifies your site on OAUTH2 vendor site
- **client\_secret**: private key associated to your site on OAUTH2 vendor site, to use in authorization code - access token exchange

To learn more how each of them work, check [specialized article](https://www.lucinda-framework.com/blog/php-oauth2-integration-explained)

Configuration
-------------

[](#configuration)

To configure this API you must have a XML with following tag:

```

		...

	...

```

Where:

- **oauth2**: (mandatory) holds global oauth2 settings.
    - {ENVIRONMENT}: name of development environment (to be replaced with "local", "dev", "live", etc)
        - **driver**: stores information about a single oauth2 provider via attributes:
            - *name*: (mandatory) name of OAuth2 provider. Can be: Facebook, GitHub, Google, LinkedIn, Instagram, VK, Yahoo, Yandex!
            - *client\_id*: (mandatory) public id that identifies your site on OAUTH2 vendor site (see: [registration](#registration))
            - *client\_secret*: (mandatory) private key associated to your site on OAUTH2 vendor site, to use in authorization code - access token exchange (see: [registration](#registration))
            - *callback*: (mandatory) relative uri (page) in your site where OAUTH2 vendor should redirect authorization code to (see: [registration](#registration)). **Must be unique!**
            - *scopes*: (optional) rights levels on client's vendor account your site require (see: [registration](#registration))
            - {OPTIONS}: a list of extra attributes not part of specifications but required by certain providers:
                - *application*: (mandatory if *provider* = GitHub) name of your site (see: [registration](#registration))

Example:

```

```

Execution
---------

[](#execution)

### Initialization

[](#initialization)

Now that XML is configured, you can get driver whose login uri matches requested page by querying [Lucinda\\OAuth2\\Wrapper](https://github.com/aherne/oauth2client/blob/master/src/Wrapper.php):

```
$requestedPage = (!empty($_SERVER["REQUEST_URI"])?substr($_SERVER["REQUEST_URI"], 1):"");
$object = new Lucinda\OAuth2\Wrapper(simplexml_load_file(XML_FILE_NAME), DEVELOPMENT_ENVIRONMENT);
$driver = $object->getDriver($requestedPage);
```

Driver returned is a [Lucinda\\OAuth2Client\\Driver](https://github.com/aherne/oauth2client/blob/master/src/Driver.php) instance, each corresponding to a "driver" tag whose callback matches requested page, each hiding complexity of vendor underneath through a common interface centered on oauth2 client operations. If no driver is found matching requested page, NULL is returned!

**NOTE**: because XML parsing is somewhat costly, it is recommended to save $object somewhere and reuse it throughout application lifecycle.

### Querying Provider

[](#querying-provider)

Once you obtain a driver, you able to query it automatically. First however you need to obtain an access token from provider in controller that handles all **REDIRECT\_URI** (since this logic is same across vendors):

```
if (empty($_GET["code"])) {
    // redirects to vendor in order to get authorization code
    $redirectURL = $driver->getAuthorizationCodeEndpoint();
    header("Location: ".$redirectURL);
    exit();
} else {
    // exchanges authorization code with an access token
    $accessTokenResponse = $driver->getAccessToken($_GET["code"]);

    // save $accessTokenResponse to storage
    // save $driver to storage
}
```

Once an access token is saved you can use it in current or future requests to authenticate resources requests on vendor. Before using it, you need to make sure token has not expired:

```
// loads $accessTokenResponse from storage
if ($accessTokenResponse->getExpiresIn() && $accessTokenResponse->getExpiresIn()>time()) {
    $accessTokenResponse = $driver->refreshAccessToken($accessTokenResponse->getRefreshToken());
    // save $accessTokenResponse to storage
}
```

Then to retrieve any resource on vendor whose scope was approved by client:

```
$accessToken = $accessTokenResponse->getAccessToken();
$information = $driver->getResource(accessToken, RESOURCE_URI, ?RESOURCE_FIELDS);
```

### Example

[](#example)

Assuming driver is:

```

```

If value of $\_SERVER\["REQUEST\_URI"\] is "login/facebook", in line of [Querying Provider](#querying-provider) above, first a check is made if "code" querystring param is present:

- NO: redirects to provider and asks client to approve access for public\_profile and email visualization rights. If approved, vendor redirects to same page but with a "code" param
- YES: asks provider to exchange short lived authorization code (value of "code" param) with a long lived access token

Now that access token is obtained, developers can use it to retrieve public\_profile and email information about client from vendor site:

```
// load $driver from storage
// load $accessToken from storage
$userInformation = $driver->getResource($accessToken, "https://graph.facebook.com/v2.8/me", ["id","name","email"]);
```

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

[](#installation)

First choose a folder, associate it to a domain then write this command there using console:

```
composer require lucinda/oauth2-client
```

Then create a *configuration.xml* file holding configuration settings (see [configuration](#configuration) above) and a *index.php* file (see [initialization](#initialization) in project root with following code:

```
require(__DIR__."/vendor/autoload.php");
$requestedPage = (!empty($_SERVER["REQUEST_URI"])?substr($_SERVER["REQUEST_URI"], 1):"");
$object = new Lucinda\OAuth2\Wrapper(simplexml_load_file("configuration.xml"), "local");
$driver = $object->getDriver($requestedPage);
```

Then make sure domain is available to world-wide-web and all request that point to it are rerouted to index.php:

```
RewriteEngine on
RewriteRule ^(.*)$ index.php

```

Unit Tests
----------

[](#unit-tests)

For tests and examples, check following files/folders in API sources:

- [test.php](https://github.com/aherne/oauth2client/blob/master/test.php): runs unit tests in console
- [unit-tests.xml](https://github.com/aherne/oauth2client/blob/master/unit-tests.xml): sets up unit tests and mocks "loggers" tag
- [tests](https://github.com/aherne/oauth2client/tree/v3.0.0/tests): unit tests for classes from [src](https://github.com/aherne/oauth2client/tree/v3.0.0/src) folder
- [tests\_drivers](https://github.com/aherne/oauth2client/tree/v3.0.0/tests_drivers): unit tests for classes from [drivers](https://github.com/aherne/oauth2client/tree/v3.0.0/drivers) folder

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity85

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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

Recently: every ~19 days

Total

45

Last Release

1437d ago

Major Versions

v1.6.6 → v2.0.02019-11-23

v2.0.10 → v3.0.02021-12-30

v2.0.11 → v4.0.0.x-dev2022-01-09

v2.1.0 → v3.0.32022-03-19

PHP version history (3 changes)v2.0.1.3PHP ^7.1

v3.0.0PHP ^8.1

v2.0.11PHP ^7.1|^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3382770?v=4)[Lucian Gabriel Popescu](/maintainers/aherne)[@aherne](https://github.com/aherne)

---

Top Contributors

[![aherne](https://avatars.githubusercontent.com/u/3382770?v=4)](https://github.com/aherne "aherne (54 commits)")

---

Tags

clientprovidersoauth2

### Embed Badge

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

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

###  Alternatives

[mollie/oauth2-mollie-php

Mollie Provider for OAuth 2.0 Client

251.7M1](/packages/mollie-oauth2-mollie-php)[omines/oauth2-gitlab

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

36721.5k13](/packages/omines-oauth2-gitlab)

PHPackages © 2026

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