PHPackages                             misarji/zend-oauth2 - 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. misarji/zend-oauth2

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

misarji/zend-oauth2
===================

Great OAuth2 client for ZF2. It provides clients for github, google, facebook and linkedin, others are coming soon.

1.0.0(11y ago)1013.4k2[1 issues](https://github.com/misarji/zend-oauth2/issues)MITPHPPHP &gt;=5.3.3

Since Aug 25Pushed 9y ago2 watchersCompare

[ Source](https://github.com/misarji/zend-oauth2)[ Packagist](https://packagist.org/packages/misarji/zend-oauth2)[ Docs](https://github.com/misarji/ZendOAuth2)[ RSS](/packages/misarji-zend-oauth2/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (1)Versions (2)Used By (0)

ZendOAuth2
==========

[](#zendoauth2)

Great OAuth2 client for ZF2. It provides clients for github, google, facebook and linkedin, others are coming soon.

The library is kept as simple as possible, it does not provide routes or controllers.

Installation with Composer
--------------------------

[](#installation-with-composer)

1. Add this project in your `composer.json`:

```
    "require": {
        "misarji/zend-auth2": "dev-master",
    }
```

2. Fetch the repository with composer:

```
$ php composer.phar update
```

3. Enable it in your `config/application.config.php` file:

```
return array(
	'modules' => array(
		// ...
		'ZendOAuth2',
	),
	// ...
);
```

Usage
-----

[](#usage)

As usual add it to your application.config.php 'ZendOAuth2'.

Copy &amp; rename the `config/zendoauth2.local.php.dist` to your autoload folder and fill the information needed.

### In your controller/action do:

[](#in-your-controlleraction-do)

```
public function callbackAction()
{

    $me = $this->getServiceLocator()->get('ZendOAuth2\Google');
    //$me = $this->getServiceLocator()->get('ZendOAuth2\Github');
    //$me = $this->getServiceLocator()->get('ZendOAuth2\Facebook');
    //$me = $this->getServiceLocator()->get('ZendOAuth2\LinkedIn');

    if (strlen($this->params()->fromQuery('code')) > 10) {

    	if($me->getToken($this->request)) {
    		$token = $me->getSessionToken(); // token in session
    	} else {
    		$token = $me->getError(); // last returned error (array)
    	}

        $info = $me->getInfo();

    } else {

        $url = $me->getUrl();

    }

    return array('token' => $token, 'info' => $info, 'url' => $url);

}
```

The action name depends on your settings. getUrl() will return the url where you should redirect the user, there is no automatic redirection do it yourself.

### Client Configuration

[](#client-configuration)

Beside the configuration options in `module.config.php` and `reverseoath2.local.php` you can change the client configuration on runtime.

```
public function callbackAction()
{

    $me = $this->getServiceLocator()->get('ZendOAuth2\Google');
    //$me = $this->getServiceLocator()->get('ZendOAuth2\Github');
    //$me = $this->getServiceLocator()->get('ZendOAuth2\Facebook');
    //$me = $this->getServiceLocator()->get('ZendOAuth2\LinkedIn');

	$me->getOptions()->setScope(array('email', 'user'));
	$me->getOptions()->setAuthUri('http://google.com/');
	$me->getOptions()->setTokenUri('http://google.com/');
	$me->getOptions()->setInfoUri('http://google.com/');
	$me->getOptions()->setClientId('my-id.com');
	$me->getOptions()->setClientSecret('my-secret');
	$me->getOptions()->setRedirectUri('http://my-server.com/');

}
```

### The ZendOAuth2 authentication adapter

[](#the-zendoauth2-authentication-adapter)

The module provides also an zend\\authentication\\adapter.

```
public function authGithubAction() // controller action
{

    $me = $this->getServiceLocator()->get('ZendOAuth2\Github');

    $auth = new AuthenticationService(); // zend

    if (strlen($this->params()->fromQuery('code')) > 10) {

        if($me->getToken($this->request)) { // if getToken is true, the user has authenticated successfully by the provider, not yet by us.
            $token = $me->getSessionToken(); // token in session
        } else {
            $token = $me->getError(); // last returned error (array)
        }

        $adapter = $this->getServiceLocator()->get('ZendOAuth2\Auth\Adapter'); // added in module.config.php
        $adapter->setOAuth2Client($me); // $me is the oauth2 client
        $rs = $auth->authenticate($adapter); // provides an eventManager 'oauth2.success'

        if (!$rs->isValid()) {
            foreach ($rs->getMessages() as $message) {
                echo "$message\n";
            }
            echo 'no valid';
        } else {
            echo 'valid';
        }

    } else {
        $url = $me->getUrl();
    }

    $view = new ViewModel(array('token' => $token, 'info' => $info, 'url' => $url, 'error' => $me->getError()));

    return $view;

}
```

The adapter also provides an event called `oauth2.success`. Here you can check the data from the client against your user registry. You will be provided with information from the user, token info and provider type.

In your module class you could do:

```
public function onBootstrap(Event $e)
{
    /* Some bad code here, only for demo purposes. */
    $userTable = new UserTable($e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter')); // my user table
    $e->getApplication()->getServiceManager()->get('ZendOAuth2\Auth\Adapter')->getEventManager() // the the adapters eventmanager
        ->attach('oauth2.success', //attach to the event
            function($e) use ($userTable){

                $params = $e->getParams(); //print_r($params); so you see whats in if

                if($user = $userTable->getUserByRemote($params['provider'], $params['info']['id'])) { // check for user from facebook with id 1000

                    $user->token = $params['token']['access_token'];
                    $expire = (isset($params['token']['expires'])) ? $params['token']['expires'] : 3600;
                    $user->token_valid = new \Zend\Db\Sql\Expression('DATE_ADD(NOW(), INTERVAL '.$expire.' SECOND)');
                    $user->date_update = new \Zend\Db\Sql\Expression('NOW()');

                    $userTable->saveUser($user);

                } else {

                    $user = new User;
                    $user->token = $params['token']['access_token'];
                    $expire = (isset($params['token']['expires'])) ? $params['token']['expires'] : 3600;
                    $user->token_valid = new \Zend\Db\Sql\Expression('DATE_ADD(NOW(), INTERVAL '.$expire.' SECOND)');
                    $user->date_update = new \Zend\Db\Sql\Expression('NOW()');
                    $user->date_create = new \Zend\Db\Sql\Expression('NOW()');
                    $user->remote_source = $params['provider'];
                    $user->remote_id = $params['info']['id'];
                    $user->name = $params['info']['name'];
                    $user->info = \Zend\Json\Encoder::encode($params['info']);

                    $userTable->saveUser($user);

                }

                $user = $userTable->getUserByRemote($params['provider'], $params['info']['id']);
                $params['info'] = $user->getArrayCopy();
                $params['info']['info'] = false;

    			// here the params info is rewitten. The result object returned from the auth object will have the db row.

    			$params['code'] = \Zend\Authentication\Result::FAILURE; // this would deny authentication. default is \Zend\Authentication\Result::SUCCESS.

            });

}
```

TODO
----

[](#todo)

- Add other clients
- Write some decent documentation.
- Demo module is on it's way.

###  Health Score

32

—

LowBetter than 74% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

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

Unknown

Total

1

Last Release

4226d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7c52f88a39f8246aa6b3abbf503d9defbdf260707acc8a557a266d24e9f9d434?d=identicon)[misarji](/maintainers/misarji)

---

Tags

oauth2modulezf2

### Embed Badge

![Health badge](/badges/misarji-zend-oauth2/health.svg)

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

PHPackages © 2026

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