Advertisement
  1. Code
  2. PHP
  3. Yii

How to Program With Yii2: Google Authentication

Scroll to top
Read Time: 8 min
This post is part of a series called How to Program With Yii2.
How to Program With Yii2: Using the Advanced Application Template
Programming With Yii2: Using Amazon S3
Final product imageFinal product imageFinal product image
What You'll Be Creating

If you're asking, "What's Yii?" check out Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of Yii 2.0.

In this Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. In this tutorial, I'll continue to guide you through integration of the built-in AuthClient, using the Google Accounts API and OAuth 2.0. 

It may be helpful for you to review Programming With Yii2: Integrating User Registration, which walks through integration of the Yii2-User library for user registration and authentication, and Programming With Yii2: AuthClient Integration With Twitter, Google and Other Networks, which explores integration with Twitter authentication and the now deprecated support for Google's OpenID. This tutorial will show you how to move from our earlier Google OpenID integration to OAuth 2.0 integration with the Google Accounts API.

For these examples, we'll continue building on the framework for the series, our hello codebase. Use the GitHub links on this page to get the download for the code repository.

Before we get started, please remember, I do try to participate in the discussions below. If you have a question or topic suggestion, please post a comment below or contact me on Twitter @reifman. You can also email me directly.

If you noticed there's been a delay in this series, it's because I'm recently back from brain surgery. Thank you for your patience and support—it's nice to be writing again regularly and I'm looking forward to continuing coverage of Yii2.

Updating Yii2 User

Since I last wrote about these topics, Yii2 User has improved a great deal. The first thing we need to do is update its library. You can do this with composer at the command line:

1
composer require "dektrium/yii2-user:0.9.*@dev"

This will automatically update composer.json:

1
"minimum-stability": "stable",
2
    "require": {
3
        "php": ">=5.4.0",
4
        "yiisoft/yii2": "*",
5
        "yiisoft/yii2-bootstrap": "*",
6
        "yiisoft/yii2-swiftmailer": "*",
7
        "dektrium/yii2-user": "0.9.*@dev",
8
        "stichoza/google-translate-php": "~2.0",
9
        "yiidoc/yii2-redactor": "2.0.0",
10
        "yiisoft/yii2-authclient": "*",
11
    },

Afterwards, run the latest database migrations for Yii2 User—this will bring your database up to date with the latest library:

1
php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations

You'll likely see something like this:

1
$ php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations
2
Yii Migration Tool (based on Yii v2.0.6)
3
4
Total 4 new migrations to be applied:
5
    m141222_110026_update_ip_field
6
	m141222_135246_alter_username_length
7
	m150614_103145_update_social_account_table
8
	m150623_212711_fix_username_notnull
9
10
Apply the above migrations? (yes|no) [no]:yes
11
*** applying m141222_110026_update_ip_field
12
    > alter column registration_ip in table {{%user}} to string(45) ... done (time: 0.009s)
13
*** applied m141222_110026_update_ip_field (time: 0.030s)
14
15
*** applying m141222_135246_alter_username_length
16
    > alter column username in table {{%user}} to string(255) ... done (time: 0.010s)
17
*** applied m141222_135246_alter_username_length (time: 0.012s)
18
19
*** applying m150614_103145_update_social_account_table
20
    > add column code string(32) to table {{%social_account}} ... done (time: 0.008s)
21
    > add column created_at integer to table {{%social_account}} ... done (time: 0.009s)
22
    > add column email string to table {{%social_account}} ... done (time: 0.008s)
23
    > add column username string to table {{%social_account}} ... done (time: 0.009s)
24
    > create unique index account_unique_code on {{%social_account}} (code) ... done (time: 0.016s)
25
*** applied m150614_103145_update_social_account_table (time: 0.059s)
26
27
*** applying m150623_212711_fix_username_notnull
28
    > alter column username in table {{%user}} to string(255) NOT NULL ... done (time: 0.009s)
29
*** applied m150623_212711_fix_username_notnull (time: 0.011s)
30
31
32
Migrated up successfully.

You also have to move the component definition for yii2-user to modules in \hello\config\web.php:

1
'modules' => [
2
          'redactor' => 'yii\redactor\RedactorModule',
3
          'class' => 'yii\redactor\RedactorModule',
4
          'uploadDir' => '@webroot/uploads',
5
          'uploadUrl' => '/hello/uploads',
6
          'user' => [
7
                'class' => 'dektrium\user\Module',
8
                'enableUnconfirmedLogin' => TRUE,
9
                'confirmWithin' => 21600,
10
                'cost' => 12,
11
                'admins' => ['admin']
12
              ],              
13
      ],

Register Your Google Project

In order for your Yii2 app users to register and log in with their Google Accounts, you'll need to register a Google Project at the Developer Console:

Programming Yii2 Google Developers ConsoleProgramming Yii2 Google Developers ConsoleProgramming Yii2 Google Developers Console

Let's Create a Project called yii2hello:

Programming Yii2 Google Developers Console New ProjectProgramming Yii2 Google Developers Console New ProjectProgramming Yii2 Google Developers Console New Project

You'll be taken to the project home page with a variety of options in the left sidebar menu:

Programming Yii2 Google Developers Console Project HomepageProgramming Yii2 Google Developers Console Project HomepageProgramming Yii2 Google Developers Console Project Homepage

It's important to request access to whichever API groups with Google we may be using. For Yii2 User, we need to enable Google+ APIs. Click on APIs & auth > APIs and search for google+:

Programming Yii2 Google Developers Console Search Programming Yii2 Google Developers Console Search Programming Yii2 Google Developers Console Search

Then, click Enable API:

Programming Yii2 Google Developers Console Enable APIProgramming Yii2 Google Developers Console Enable APIProgramming Yii2 Google Developers Console Enable API

You'll see a list of the Enabled APIs which now includes the Google+ API:

Programming Yii2 Google Developers Console List Enabled APIsProgramming Yii2 Google Developers Console List Enabled APIsProgramming Yii2 Google Developers Console List Enabled APIs

Next, we need to add credentials so we can authenticate our API requests with Google for this project's activities. Click Credentials:

Programming Yii2 Google Developers Console CredentialsProgramming Yii2 Google Developers Console CredentialsProgramming Yii2 Google Developers Console Credentials

Let's use the OAuth 2.0 client ID option above. You'll then be asked to create an OAuth Consent Screen and fill in information about your application which will be presented to users trying to register or sign in with your application:

Programming Yii2 Google Developers Console OAuth ConsentProgramming Yii2 Google Developers Console OAuth ConsentProgramming Yii2 Google Developers Console OAuth Consent

On the Credentials page, we'll choose Web application, and since we're testing locally, we'll provide two settings for authentication callbacks. I use port 8888 for my local development. So, my Authorized JavaScript origins will be http://localhost:8888 and Yii2 User requires the Authorized redirect URIs path of http://localhost:8888/hello/user/security/auth?authclient=google.

Programming Yii2 Google Developers Console Project SettingsProgramming Yii2 Google Developers Console Project SettingsProgramming Yii2 Google Developers Console Project Settings

You'll be presented with API keys, also known as a client ID and client secret:

I'll review where to place those keys below.

Configuring the AuthClient Support

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. 

In my /var/secure/hello.ini file, I store all the keys for my application—place your Google API keys inside here as well:

1
oauth_google_clientId="41xxxxxxxxxxxxxeusercontent.com"
2
oauth_google_clientSecret="LmxxxxxxxxxxxxxxxxxxxxxxFJ4"
3
oauth_twitter_key ="rxkxxxxxxxxxxxxxxxxxopjU"
4
oauth_twitter_secret="b7gU4twxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxkLy0z2e"
5
smtp_host = "mailtrap.io"
6
smtp_username = "2xxxxxxxxxxxxxxxxx2"
7
smtp_password = "2xxxxxxxxxxxxxxxxx5"
8
mysql_host="localhost"
9
mysql_un="xxxxxxxxxxxx"
10
mysql_db="hello"
11
mysql_pwd="xxxxxxxxxxxx"

We need to add references to these keys in the AuthClient configuration settings in our web configuration file in \config\web.php. Add array elements for all of the third-party services that you wish to support:

1
<?php
2
$config = parse_ini_file('/var/secure/hello.ini', true);
3
$params = require(__DIR__ . '/params.php');
4
$config = [
5
    'id' => 'basic',
6
    'basePath' => dirname(__DIR__),
7
    'bootstrap' => ['log'],
8
    'language'=>'en', // back to English

9
    'components' => [
10
      'view' => [
11
              'theme' => [
12
                  'pathMap' => [
13
                      '@dektrium/user/views' => '@app/views/user'
14
                  ],
15
              ],
16
          ],    
17
      'authClientCollection' => [
18
              'class' => 'yii\authclient\Collection',
19
              'clients' => [
20
                  'google' => [
21
                      'class'        => 'dektrium\user\clients\Google',
22
                      'clientId'     => $config['oauth_google_clientId'],
23
                      'clientSecret' => $config['oauth_google_clientSecret'],
24
                  ],
25
                  'twitter' => [
26
                                  'class' => 'yii\authclient\clients\Twitter',
27
                                  'consumerKey' => $config['oauth_twitter_key'] ,
28
                                  'consumerSecret' => $config['oauth_twitter_secret'] ,
29
                              ],
30
                ],
31
        ],

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.

MailTrap SMTP SettingsMailTrap SMTP SettingsMailTrap SMTP Settings

For this tutorial, I found I had to update port information for SwiftMailer to 2525 in \config\web.php:

1
'mailer' => [
2
                'class' => 'yii\swiftmailer\Mailer',
3
                'viewPath' => '@app/mailer',
4
                'useFileTransport' => false,
5
                'transport' => [
6
                    'class' => 'Swift_SmtpTransport',
7
                    'host' => $config['smtp_host'],
8
                    'username' => $config['smtp_username'],
9
                    'password' => $config['smtp_password'],
10
                    'port' => '2525',
11
                    'encryption' => 'tls',
12
                                ],
13
            ],

Registering With Your Google Account

Now, we're finally ready to explore using Yii2 User's front-end interface. Let's begin with registration. Click on the Sign Up option in the menu and you'll see this form:

Yii2 User Hello App Sign UpYii2 User Hello App Sign UpYii2 User Hello App Sign Up

To register with all we've created today, click the Google+ icon. Because I'm only logged into one Google account, there will be a transparent popup and redirect to complete my registration:

Yii2 User Hello App Sign Up CompletionYii2 User Hello App Sign Up CompletionYii2 User Hello App Sign Up Completion

You should see the home page showing that you're authenticated in the upper right corner:

Yii2 User Hello App Signed InYii2 User Hello App Signed InYii2 User Hello App Signed In

Signing In With Your Google Account

Click Logout and then we can try signing in with the Google+ icon. Click Sign In in the header menu:

Yii2 User Hello App Sign InYii2 User Hello App Sign InYii2 User Hello App Sign In

Then, click the Google+ icon again. You'll be taken right to the home screen showing that you're logged in again. Pretty cool, huh? But, what if you're logged in to two Google accounts?

Yii2 User Hello App Sign In with Multiple AccountsYii2 User Hello App Sign In with Multiple AccountsYii2 User Hello App Sign In with Multiple Accounts

When you select your Google account to sign in with, you'll be taken back to the home page in authenticated mode.

The User Profile and Connection Area

While it's not yet configured in our Bootstrap header menu, if you visit  http://localhost:8888/hello/user/settings/networks, you'll see the new connection interface for third-party accounts within Yii2 User:

Yii2 User Hello App Network Page to ConnectYii2 User Hello App Network Page to ConnectYii2 User Hello App Network Page to Connect

Once signed in, your users can connect and disconnect their social accounts from here. There's also an account management and user profile area. It's pretty nicely done. 

You may want to check out my Building Your Startup With PHP series, which uses Yii2's advanced template with third-party integration, currently without Yii2 User. However, there is now a guide to integrating Yii2 User with the advanced template, so I may update this soon.

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. 

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.