Yii Framework 2.x

Updated May 30th 2018

Tested with Yii Framework 2 Version: 2.0.15

yii2-authclient

Step-by-step installation guide

These instructions require yii2-authclient version 2.1.6 which is not released at time of writing. Please check here to see whether 2.1.6 is released before starting or use the master branch.
This tutorial is based off the Yii Framework 2.0 Basic template but the behaviour for the Advanced template is largely the same, just with different namespaces.

yii2-authclient is a core maintained plugin for Yii2 that provides OAuth2 and OpenID Connect functionality.

Using the yii2-authclient, you can connect your Yii2-based application to PixelPin and allow your users to authenticate with pictures instead of passwords.

To complete the installation, you will need to create a PixelPin developer account.

Download and install your Yii 2 Application

Downloading an example website allows you to understand how to install the yii2-authclient without breaking a live site during development.

Yii2 requires a minimum PHP version of 5.4 but version 7.x or higher is recommended for newer installations since it is much faster and removes much older functionality that is no longer required for Yii2 and other frameworks.

As with many PHP frameworks, Yii2 makes heavy use of Composer for installing both the framework and other packages. If you have not done so, you need to download and install both PHP (Linux) or PHP (Windows) and Composer before continuing.

You will need to ensure that the PHP extensions for curl, intl, fileinfo and gmp are enabled in your php.ini. These are available in the standard distributions.

Click on the link to find a guide for Installing Yii.

Installation of the plugin

The following instructions are available here but are repeated below for clarity.
  1. From your Yii2 project root directory, run composer require --prefer-dist yiisoft/yii2-authclient:~2.1.0 spomky-labs/jose in your favourite CLI. The output should show about 10 packages installed and look something like this:

If this is the first time you have run composer, you might get errors either about your environment or about extensions that PHP requires but are not enabled on your system. Note that composer is using the CLI version of PHP which can come from a different place to your local web php handler. Type php -v to find out which version of PHP is being used.

Read the suggestions to decide whether you want to install the extensions. PixelPin does not make use of EC or AES cryptography in OpenID Connect but you might want the extensions for other parts of your system.

Configuring the plugin

  1. If you do not already have one, you will need to create a user database table using these instructions.
  2. You will need to create a new database table called auth if you have not already installed this plugin. You can create this in a migration or directly in the database(s), see here for the table schema. Don't forget the foreign key.

  3. Using Gii in Yii2, create an Auth model in the models namespace (or common\models in the advanced template) based on the auth table just created. Do the same for the user table if there is not already a model present for User.
  4. Add configuration for the PixelPin provider into your config\main-local.php file (or common\config\main-local.php in the advanced template). You will not be able to set the client id and secret yet.
  5. return [
        'components' => [
            'authClientCollection' => [
                'class' => 'yii\authclient\Collection',
                'clients' => [
                    'pixelpin' => [
                        'class' => 'yii\authclient\OpenIdConnect',
                        'issuerUrl' => 'https://login.pixelpin.io',
                        'clientId' => 'pixelpin_client_id',
                        'clientSecret' => 'pixelpin_client_secret',
                        'name' => 'PixelPin',
                        'title' => 'Login with a picture',
                        'scope' => 'openid email'
                    ],
                    // etc.
                ],
            ]
            // ...
        ],
        // ...
    ];
                        
    The provider configuration contains a secret and should not usually be kept in source control. Yii2 uses the concept of local files, which are gitignored and which allow a local file in production and a different local file in development with different credentials in each. For example, the development ones will use a different hostname for the redirect uri and a different PixelPin developer account, which can easily be deleted if the developer code is compromised, without affecting the production account.
  6. You will need to add an action to a controller that maps to the AuthAction class in the plugin. The example below, taken from the plugin docs uses the action auth in SiteController. The success handler will need to map to an "AuthHandler" class, which you will create next. The namespace for your AuthHandler at the top of SiteController might need changing once you know where you are going to create AuthHandler.
  7. use app\components\AuthHandler;
    
    class SiteController extends Controller
    {
        public function actions()
        {
            return [
                'auth' => [
                    'class' => 'yii\authclient\AuthAction',
                    'successCallback' => [$this, 'onAuthSuccess'],
                ],
            ];
        }
    
        public function onAuthSuccess($client)
        {
            (new AuthHandler($client))->handle();
        }
    }
  8. You will need an AuthHandler class to handle the logic of redirecting back from PixelPin. In the basic template of Yii2, the default location is under the components directory, which matches the controller code above. In the advanced template, you can either put it under common\components if it is shared between the frontend and backend sites or just under frontend\components if only for the front end.

    The example code can be found here but there are some things to consider before simply copying and pasting the code. By default, it does most of what you would want like matching external accounts to the local user accounts and saving an Auth entry for the link, creating new local accounts if there isn't one already but you need to also consider:

    • The example shows a field called "github" that does not exist in the default user model (or the one from their migration code) but is present to show how a custom field could be updated every time the user logs in. You might not want this but the code will not work as shown so if you don't, you should remove references to github and the updateUserInfo function (or replace github with another custom field).
    • OpenIdConnect (and therefore PixelPin) defines the names of the user fields as sub and nickname. These need changing from id and login.
    • Depending on whether you want additional information returned from PixelPin, you need to modify the scope value in your configuration to include "profile" but as with most providers, only the sub and email are guaranteed to come back, other fields might be blank/null for some or all users.
    • The default code does not handle a user having a nickname that matches an existing account with a different email i.e. a conflicting username, and will error when it tries to save the new user. You can use some additional code to generate a unique id or write your own code to allow the user to set their own username (checking that it is available before letting them save it).
  9. There is a widget available to display the auth providers. Unfortunately, it does not currently work by default with custom providers like PixelPin, only with built-in providers. You can still use it but you will have to apply some css styles to make it visible (it is physically present but blank) or alternatively, use the custom widget display shown below and style it as you wish:
  10. <?php
         use yii\authclient\widgets\AuthChoice;
     ?>
     <?php $authAuthChoice = AuthChoice::begin([
         'baseAuthUrl' => ['site/auth']
     ]); ?>
     <ul>
     <?php foreach ($authAuthChoice->getClients() as $client): ?>
         <li><?= $authAuthChoice->clientLink($client) ?></li>
     <?php endforeach; ?>
     </ul>
     <?php AuthChoice::end(); ?>
  11. If you have used the defaults above, the redirect uri that you will need to create a developer account will be in the form https://yourhost.name/site/auth

    Once you have created and verified your developer account, copy and paste the client id and secret into your configuration. You do not need the mobile key.

  12. The application is now ready for use.

Additional Information

Click here to find out how you can add the PixelPin logo to the SSO button.

Contributing

yii2-authclient is an open-source project that allows the community to improve OpenID Connect support in their Yii2 apps. You can find the repository link below:

  1. Yii2 Authclient