PHPackages                             admad/cakephp-social-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. admad/cakephp-social-auth

ActiveCakephp-plugin[Authentication &amp; Authorization](/categories/authentication)

admad/cakephp-social-auth
=========================

A CakePHP plugin which allows you to authenticate using social providers like Facebook/Google/Twitter etc.

2.2.0(4mo ago)51298.3k↑36.7%23[4 issues](https://github.com/ADmad/cakephp-social-auth/issues)1MITPHPPHP &gt;=8.1CI passing

Since Jul 8Pushed 4mo ago6 watchersCompare

[ Source](https://github.com/ADmad/cakephp-social-auth)[ Packagist](https://packagist.org/packages/admad/cakephp-social-auth)[ GitHub Sponsors](https://github.com/ADmad)[ RSS](/packages/admad-cakephp-social-auth/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (30)Used By (1)

CakePHP SocialAuth Plugin
=========================

[](#cakephp-socialauth-plugin)

[![Total Downloads](https://camo.githubusercontent.com/722ffb20d9c423c99ba0273ec25b39f6ef479da17bed5f1c13b719ef2413f3da/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f41446d61642f63616b657068702d736f6369616c2d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/admad/cakephp-social-auth)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)

A CakePHP plugin which allows you authenticate using social providers like Facebook/Google/Twitter etc. using [SocialConnect/auth](https://github.com/SocialConnect/auth)social sign on library.

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

[](#installation)

Run:

```
composer require admad/cakephp-social-auth

```

Setup
-----

[](#setup)

Load the plugin by running the following command in the terminal:

```
bin/cake plugin load ADmad/SocialAuth

```

Database
--------

[](#database)

This plugin requires a migration to generate a `social_profiles` table, and it can be generated via the official Migrations plugin as follows:

```
bin/cake migrations migrate -p ADmad/SocialAuth
```

Usage
-----

[](#usage)

### Middleware config

[](#middleware-config)

The plugin provides a `\ADmad\SocialAuth\Middleware\SocialAuthMiddleware` which handles authentication process through social providers.

You can configure the middleware in your `Application::middleware()` method as shown:

```
// src/Application.php

// Be sure to add SocialAuthMiddleware after RoutingMiddleware
$middlewareQueue->add(new \ADmad\SocialAuth\Middleware\SocialAuthMiddleware([
    // Request method type use to initiate authentication.
    'requestMethod' => 'POST',
    // Login page URL. In case of auth failure user is redirected to login
    // page with "error" query string var.
    'loginUrl' => '/users/login',
    // URL to redirect to after authentication (string or array).
    'loginRedirect' => '/',
    // Boolean indicating whether user identity should be returned as entity.
    'userEntity' => true, // Compatibility with default CakePHP auth plugins
    // User model.
    'userModel' => 'Users',
    // Social profile model.
    'socialProfileModel' => 'ADmad/SocialAuth.SocialProfiles',
    // Finder type.
    'finder' => 'all',
    // Fields.
    'fields' => [
        'password' => 'password',
    ],
    // Session key to which to write identity record to.
    'sessionKey' => 'Auth',
    // The method in user model which should be called in case of new user.
    // It should return a User entity.
    'getUserCallback' => 'getUser',
    // SocialConnect Auth service's providers config. https://github.com/SocialConnect/auth/blob/master/README.md
    'serviceConfig' => [
        'provider' => [
            'facebook' => [
                'applicationId' => '',
                'applicationSecret' => '',
                'scope' => [
                    'email',
                ],
                'options' => [
                    'identity.fields' => [
                        'email',
                        // To get a full list of all possible values, refer to
                        // https://developers.facebook.com/docs/graph-api/reference/user
                    ],
                ],
            ],
            'google' => [
                'applicationId' => '',
                'applicationSecret' => '',
                'scope' => [
                    'https://www.googleapis.com/auth/userinfo.email',
                    'https://www.googleapis.com/auth/userinfo.profile',
                ],
            ],
        ],
    ],
    // Instance of `\SocialConnect\Auth\CollectionFactory`. If none provided one will be auto created. Default `null`.
    'collectionFactory' => null,
    // Whether social connect errors should be logged. Default `true`.
    'logErrors' => true,
]));
```

### Login links

[](#login-links)

On your login page you can create links to initiate authentication using required providers. E.g.

```
echo $this->Form->postLink(
    'Login with Facebook',
    [
        'prefix' => false,
        'plugin' => 'ADmad/SocialAuth',
        'controller' => 'Auth',
        'action' => 'login',
        'provider' => 'facebook',
        '?' => ['redirect' => $this->request->getQuery('redirect')]
    ]
);
```

We use a `POST` link here instead of a normal link to prevent search bots and other crawlers from following the link. If you prefer using GET you can still do so by configuring the middleware with `'requestMethod' => 'GET'`. In this case it's advisable to add `nofollow` attribute to the link.

### Authentication process

[](#authentication-process)

Depending on the provider name in the login URL the authentication process is initiated.

Once a user is authenticated through the provider, the middleware gets the user profile from the identity provider and using that tries to find the corresponding user record using the user model. If no user is found it calls the `getUser` method of your user model. The method recieves social profile model entity and session instance as argument and must return an entity for the user.

```
// src/Model/Table/UsersTable.php
use \Cake\Datasource\EntityInterface;
use \Cake\Http\Session;

public function getUser(EntityInterface $profile, Session $session)
{
    // Make sure here that all the required fields are actually present
    if (!$profile->email) {
        throw new \RuntimeException('Could not find email in social profile.');
    }

    // If you want to associate the social entity with currently logged in user
    // use the $session argument to get user id and find matching user entity.
    $userId = $session->read('Auth.id');
    if ($userId) {
        return $this->get($userId);
    }

    // Check if user with same email exists. This avoids creating multiple
    // user accounts for different social identities of same user. You should
    // probably skip this check if your system doesn't enforce unique email
    // per user.
    $user = $this->find()
        ->where(['email' => $profile->email])
        ->first();

    if ($user) {
        return $user;
    }

    // Create new user account
    $user = $this->newEntity(['email' => $profile->email]);
    $user = $this->save($user);

    if (!$user) {
        throw new \RuntimeException('Unable to save new user');
    }

    return $user;
}
```

Instead of adding a `getUser` method to your `UsersTable` you can also setup a listener for the `SocialAuth.createUser` callback and return a `User` entity from the listener callback, in a similar way as shown above.

Upon successful authentication the user identity is persisted to the session under the key you have specified in the middleware config (`Auth.User` by default).

After that the user is redirected to protected page they tried to access before login or to the URL specified in `loginRedirect` config.

In case of authentication failure the user is redirected back to login URL.

### Events

[](#events)

#### SocialAuth.createUser

[](#socialauthcreateuser)

After authentication from the social auth provider if a related use record is not found then `SocialAuth.createUser` is triggered. As an alternative to adding a new `createUser()` method in your `UsersTable` as mentioned above you can instead use this event to return an entity for a new user.

#### SocialAuth.afterIdentify

[](#socialauthafteridentify)

Upon successful authentication a `SocialAuth.afterIdentify` event is dispatched with the user entity. You can setup a listener for this event to perform required tasks. The listener can optionally return a user entity as event result.

#### SocialAuth.beforeRedirect

[](#socialauthbeforeredirect)

After the completion of authentication process before the user is redirected to required URL a `SocialAuth.beforeRedirect` event is triggered. This event for e.g. can be used to set a visual notification like flash message to indicate the result of the authentication process to the user.

Here's an e.g. listener with callbacks to the above method:

```
// src/Event/SocialAuthListener.php

namespace App\Event;

use ADmad\SocialAuth\Middleware\SocialAuthMiddleware;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\Event\EventListenerInterface;
use Cake\Http\ServerRequest;
use Cake\I18n\FrozenTime;
use Cake\ORM\Locator\LocatorAwareTrait;

class SocialAuthListener implements EventListenerInterface
{
    use LocatorAwareTrait;

    public function implementedEvents(): array
    {
        return [
            SocialAuthMiddleware::EVENT_AFTER_IDENTIFY => 'afterIdentify',
            SocialAuthMiddleware::EVENT_BEFORE_REDIRECT => 'beforeRedirect',
            // Uncomment below if you want to use the event listener to return
            // an entity for a new user instead of directly using `createUser()` table method.
            // SocialAuthMiddleware::EVENT_CREATE_USER => 'createUser',
        ];
    }

    public function afterIdentify(EventInterface $event, EntityInterface $user): EntityInterface
    {
        // Update last login time
        $user->set('last_login', new FrozenTime());

        // You can access the profile using $user->social_profile

        $this->getTableLocator()->get('Users')->saveOrFail($user);

        return $user;
    }

    /**
     * @param \Cake\Event\EventInterface $event
     * @param string|array $url
     * @param string $status
     * @param \Cake\Http\ServerRequest $request
     * @return void
     */
    public function beforeRedirect(EventInterface $event, $url, string $status, ServerRequest $request): void
    {
        // Set flash message
        switch ($status) {
            case SocialAuthMiddleware::AUTH_STATUS_SUCCESS:
                $request->getFlash()->error('You are now logged in.');
                break;

            // Auth through provider failed. Details will be logged in
            // `error.log` if `logErrors` option is set to `true`.
            case SocialAuthMiddleware::AUTH_STATUS_PROVIDER_FAILURE:

            // Table finder failed to return user record. An e.g. of this is a
            // user has been authenticated through provider but your finder has
            // a condition to not return an inactivated user.
            case SocialAuthMiddleware::AUTH_STATUS_FINDER_FAILURE:
                $request->getFlash()->error('Authentication failed.');
                break;

            case SocialAuthMiddleware::AUTH_STATUS_IDENTITY_MISMATCH:
                $request->getFlash()->error('The social profile is already linked to another user.');
                break;
        }

        // You can return a modified redirect URL if needed.
    }

    public function createUser(EventInterface $event, EntityInterface $profile, Session $session): EntityInterface
    {
        // Create and save entity for new user as shown in "createUser()" method above

        return $user;
    }
}
```

Attach the listener in your `Application` class:

```
// src/Application.php
use App\Event\SocialAuthListener;
use Cake\Event\EventManager;

// In Application::bootstrap() or Application::middleware()
EventManager::instance()->on(new SocialAuthListener());
```

### Extend with custom providers

[](#extend-with-custom-providers)

In order to enable custom providers (those not pre-included with `SocialConnect/Auth`) you can extend the middleware configuration with `collectionFactory` and passing in your own instance of `SocialConnect\Auth\CollectionFactory`.

For e.g. create your custom provider at `src/Authenticator/MyProvider.php`. Check the providers in `vendor/socialconnect/auth/src/(OAuth1|OAuth2|OpenIDConnect)/Provider/`for examples.

Create an instance of `CollectionFactory`.

```
$collectionFactory = new \SocialConnect\Auth\CollectionFactory();
$collectionFactory->register(\App\Authenticator\MyProvider::NAME, \App\Authenticator\MyProvider::class);
```

Then set the factory instance in the middlware config shown above:

```
...
'collectionFactory' => $collectionFactory
...

```

Copyright
---------

[](#copyright)

Copyright 2017-Present ADmad

License
-------

[](#license)

[See LICENSE](LICENSE.txt)

###  Health Score

62

—

FairBetter than 99% of packages

Maintenance74

Regular maintenance activity

Popularity49

Moderate usage in the ecosystem

Community25

Small or concentrated contributor base

Maturity83

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 80.9% 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 ~115 days

Recently: every ~203 days

Total

28

Last Release

132d ago

Major Versions

0.x-dev → 1.0.0-beta2020-11-15

1.3.0 → 2.0.02023-10-15

1.x-dev → 2.2.02026-01-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/e31753bdd616948c7c8978ea9b5805378f75bfa62564e69c0aa2fd67aaf418c5?d=identicon)[ADmad](/maintainers/ADmad)

---

Top Contributors

[![ADmad](https://avatars.githubusercontent.com/u/142658?v=4)](https://github.com/ADmad "ADmad (148 commits)")[![dereuromark](https://avatars.githubusercontent.com/u/39854?v=4)](https://github.com/dereuromark "dereuromark (15 commits)")[![josegonzalez](https://avatars.githubusercontent.com/u/65675?v=4)](https://github.com/josegonzalez "josegonzalez (10 commits)")[![LordSimal](https://avatars.githubusercontent.com/u/9105243?v=4)](https://github.com/LordSimal "LordSimal (2 commits)")[![cleptric](https://avatars.githubusercontent.com/u/6617432?v=4)](https://github.com/cleptric "cleptric (2 commits)")[![ndru123](https://avatars.githubusercontent.com/u/8427961?v=4)](https://github.com/ndru123 "ndru123 (2 commits)")[![Iandenh](https://avatars.githubusercontent.com/u/2911923?v=4)](https://github.com/Iandenh "Iandenh (1 commits)")[![makkus183](https://avatars.githubusercontent.com/u/2034761?v=4)](https://github.com/makkus183 "makkus183 (1 commits)")[![jojomartius](https://avatars.githubusercontent.com/u/8529718?v=4)](https://github.com/jojomartius "jojomartius (1 commits)")[![ovr](https://avatars.githubusercontent.com/u/572096?v=4)](https://github.com/ovr "ovr (1 commits)")

---

Tags

cakephp-pluginmiddlewareoauth2phpsocial-providers

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/admad-cakephp-social-auth/health.svg)

```
[![Health](https://phpackages.com/badges/admad-cakephp-social-auth/health.svg)](https://phpackages.com/packages/admad-cakephp-social-auth)
```

###  Alternatives

[cakedc/users

Users Plugin for CakePHP

524897.0k16](/packages/cakedc-users)[dereuromark/cakephp-tinyauth

A CakePHP plugin to handle user authentication and authorization the easy way.

129228.6k10](/packages/dereuromark-cakephp-tinyauth)[admad/cakephp-jwt-auth

CakePHP plugin for authenticating using JSON Web Tokens

160680.3k8](/packages/admad-cakephp-jwt-auth)[markstory/acl_extras

Additional tools for managing DB ACL in CakePHP applications.

155311.0k](/packages/markstory-acl-extras)[cakedc/auth

Auth objects for CakePHP

31630.0k2](/packages/cakedc-auth)[uafrica/oauth-server

OAuth Server for CakePHP 3 using the PHP League's OAuth2 Server

5172.1k](/packages/uafrica-oauth-server)

PHPackages © 2026

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