If you're asking, "What's Yii?" check out my earlier tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released in October 2014.
In this Programming With Yii2 series, I'm guiding readers in use of the newly upgraded Yii2 Framework for PHP. In this tutorial, I'll guide you through integration of the built-in AuthClient support to provide sign-in from third party networks such as Twitter, Google and Facebook.
For these examples, we'll continue to imagine we're building a framework for posting simple status updates, e.g. our own mini-Twitter, using our hello codebase. Use the GitHub links on this page to download the code repository.
In Programming With Yii2: Integrating User Registration, I walked through integration of the Yii2-User library for user registration and authentication. In this tutorial, we'll learn how to integrate AuthClient with Yii2-User and override its views.
Just a reminder, I do participate in the discussions below. If you have a question or topic suggestion, please post a comment below. You can also reach me on Twitter @reifman or email me at Lookahead Consulting.
What Is AuthClient?
AuthClient is Yii's built-in support for your applications to authenticate via third-party services with OpenID, OAuth or OAuth2.
For example, AuthClient provides support for new visitors to register and sign in to your application using their Twitter account instead of having to provide a password.
Out of the box, support for the following clients is provided:
- GitHub
- Google (via OpenID and OAuth)
- Microsoft Live
- Also popular Russian services VKontakte and Yandex (via OpenID and OAuth)
Configuration for each client is a bit different. For OAuth it's required to get client ID and secret key from the service you're going to use. For OpenID it works out of the box in most cases.
For this tutorial, I'll walk you through adding Twitter and Google authentication.
Installing AuthClient in Our Application
Add AuthClient to Composer
First, we need to add the AuthClient library to composer.json:
"minimum-stability": "stable", "require": { "php": ">=5.4.0", "yiisoft/yii2": "*", "yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-swiftmailer": "*", "dektrium/yii2-user": "0.8.2", "stichoza/google-translate-php": "~2.0", "yiidoc/yii2-redactor": "2.0.0", "yiisoft/yii2-authclient": "*" },
Then, we need to update composer:
sudo composer update Password: Loading composer repositories with package information Updating dependencies (including require-dev) - Removing bower-asset/jquery.inputmask (3.1.58) - Installing bower-asset/jquery.inputmask (3.1.61) Loading from cache Writing lock file Generating autoload files
Configuring AuthClient Support
We need to add the AuthClient configuration settings to our web configuration file in \config\web.php
.
Add array elements for all of the third-party services that you wish to support (details for each can be found in the AuthClient Guide). For now, we'll use placeholder keys for Twitter.
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'language'=>'en', // back to English 'components' => [ 'authClientCollection' => [ 'class' => 'yii\authclient\Collection', 'clients' => [ 'google' => [ 'class' => 'yii\authclient\clients\GoogleOpenId' ], 'twitter' => [ 'class' => 'yii\authclient\clients\Twitter', 'consumerKey' => 'twitter_consumer_key', 'consumerSecret' => 'twitter_consumer_secret', ], ], ],
Google will work out of the box without additional configuration, but for Twitter, we need to register an application.
Register Our Twitter Application
Create a new Twitter application at the Twitter Application Dashboard:
Click Create New App. I found that the callback URL was unnecessary, but for now I used the placeholder http://mydomain.com/user/security/auth.
Here's the new page for our application:
Here's the Settings page:
Here's the Keys and Access Tokens page. Here, we need to copy the Consumer Key (API Key) and Consumer Secret (API Secret):
We'll make use of those keys in a moment.
Protecting Keys From GitHub
In Protecting Your Keys from GitHub, I described in detail how I use a configuration file to store all of my keys apart from my GitHub repository. Then, I include this file at the beginning of my Yii configuration files. This keeps me from accidentally checking in my keys to my repository and compromising my accounts.
Also, in Introduction to MailTrap: A Fake SMTP Server for Pre-Production Testing of Application Email, I began integrating MailTrap's custom SMTP settings into my Yii SwiftMailer configuration for testing purposes. This will ensure we receive the registration emails when we sign up on our local development platform.
We place both the Twitter Application keys and the MailTrap SMTP keys into /var/secure/hello.ini
outside the repository:
oauth_twitter_key ="xxxxxxxxxxxxxxxxxx" oauth_twitter_secret="xxxxxyyyyzzzzzzz222222x1111xx" smtp_host = "mysmtp.com" smtp_username = "apple12345678" smtp_password = "yyyzz!!!!32vd"
Here's the code in \config\web.php
which includes these settings and sets the individual configuration variables:
<?php $config = parse_ini_file('/var/secure/hello.ini', true); $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'language'=>'en', // back to English 'components' => [ 'authClientCollection' => [ 'class' => 'yii\authclient\Collection', 'clients' => [ 'google' => [ 'class' => 'yii\authclient\clients\GoogleOpenId' ], 'twitter' => [ 'class' => 'yii\authclient\clients\Twitter', 'consumerKey' => $config['oauth_twitter_key'] , 'consumerSecret' => $config['oauth_twitter_secret'] , ], ], ],
Further below, here's how we configure the SMTP settings for SwiftMailer:
'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@app/mailer', 'useFileTransport' => false, 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => $config['smtp_host'], 'username' => $config['smtp_username'], 'password' => $config['smtp_password'], 'port' => '25', 'encryption' => 'tls', ], ],
Updating the Database Schema to Store Session Keys
Because we're using Yii2-User, it's already provided a Token table for storing the AuthClient keys.
use yii\db\Schema; use dektrium\user\migrations\Migration; /** * @author Dmitry Erofeev <[email protected]> */ class m140504_130429_create_token_table extends Migration { public function up() { $this->createTable('{{%token}}', [ 'user_id' => Schema::TYPE_INTEGER . ' NOT NULL', 'code' => Schema::TYPE_STRING . '(32) NOT NULL', 'created_at' => Schema::TYPE_INTEGER . ' NOT NULL', 'type' => Schema::TYPE_SMALLINT . ' NOT NULL' ], $this->tableOptions); $this->createIndex('token_unique', '{{%token}}', ['user_id', 'code', 'type'], true); $this->addForeignKey('fk_user_token', '{{%token}}', 'user_id', '{{%user}}', 'id', 'CASCADE', 'RESTRICT'); } public function down() { $this->dropTable('{{%token}}'); } }
We'll examine the contents of this table at the end of this tutorial, after we've registered via Twitter.
Add the AuthClient Widget to the User Interface
The Yii2-User login page displays its Connect widget for AuthClient services on the sign-in page—notice the Google and Twitter icons at the bottom of the page:
For some reason, however, they are not included on the registration sign-up page. This seems like an oversight to me.
In order to modify the sign-up page, we need to override the registration view. Fortunately, Yii and Yii2-user make this easy—see also Overriding Views in Yii2‑User.
Returning to \config\web.php
, we add the view component below:
<?php $config = parse_ini_file('/var/secure/hello.ini', true); $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'language'=>'en', // back to English 'components' => [ 'view' => [ 'theme' => [ 'pathMap' => [ '@dektrium/user/views' => '@app/views/user' ], ], ], 'authClientCollection' => [
Then we place our own modified version of Yii2-User's register.php in @app/views/user/registration/register.php
. When the registration page is requested, Yii will load our version, which includes the Connect widget:
<?php /* * This file is part of the Dektrium project. * * (c) Dektrium project <http://github.com/dektrium> * * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ use yii\helpers\Html; use yii\widgets\ActiveForm; use dektrium\user\widgets\Connect; /** * @var yii\web\View $this * @var yii\widgets\ActiveForm $form * @var dektrium\user\models\User $user */ $this->title = Yii::t('user', 'Sign up'); $this->params['breadcrumbs'][] = $this->title; ?> <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><?= Html::encode($this->title) ?></h3> </div> <div class="panel-body"> <?php $form = ActiveForm::begin([ 'id' => 'registration-form', ]); ?> <?= Connect::widget([ 'baseAuthUrl' => ['/user/security/auth'] ]) ?> <?= $form->field($model, 'username') ?> <?= $form->field($model, 'email') ?> <?php if (Yii::$app->getModule('user')->enableGeneratingPassword == false): ?> <?= $form->field($model, 'password')->passwordInput() ?> <?php endif ?> <?= Html::submitButton(Yii::t('user', 'Sign up'), ['class' => 'btn btn-success btn-block']) ?> <?php ActiveForm::end(); ?> </div> </div> <p class="text-center"> <?= Html::a(Yii::t('user', 'Already registered? Sign in!'), ['/user/security/login']) ?> </p> </div> </div>
Here's our sign-up page now:
User Experience of Connecting via Services
Here's what the sign-up process looks like. When you click on the Twitter icon above, it will ask you to sign in to your Twitter account:
Then it will ask you to authorize the application with your account:
Then it will take you to the Connect registration form in our application—this page is also provided by Yii2-User:
When you click Finish, it inserts your OAuth token into the Token table and redirects you to the home page fully authenticated with our application:
Here's a peek inside the Token table, which stores the service session keys for each user:
On subsequent sign-in attempts, Twitter will redirect you without requiring additional authorization.
That's how we integrate third-party services into the Yii2 basic application template with Yii2-User. I hope you're pleased by how straightforward this is.
You may want to check out our Building Your Startup With PHP series, which will be using Yii2's advanced template with third party integration (apart from Yii2-User).
What's Next?
Watch for upcoming tutorials in my Programming With Yii2 series as I continue diving into different aspects of the framework.
I welcome feature and topic requests. You can post them in the comments below or email me at my Lookahead Consulting website.
If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page. My instructor page will include all the articles from this series as soon as they are published.
-
Guide to AuthClient Extension for Yii 2
- Yii2 OAuth2 Library Documentation
- Yii2 Developer Exchange, my Yii2 resource site
- A Collection of Yii-Based Scripts on CodeCanyon
Comments