Facebook Authentication using Yii2 authclient

Allowing user to login or register using some social media account is very common these days. This way user doesn't need to remember multiple username and passwords and can enjoy using one account to login into multiple platforms.

Most of the social media providers uses OAuth or OAuth 2.0 protocol and requires developers to follow a certain procedure in order to implement such functionality in applications.

Yii2 provides support for OAuth 1/1.0a, OAuth 2 and OpenID protocols out of the box using its yii2-authclient extension.

Different services implement these authentication protocols differently. To handle these differences and provide common public API, Yii2-authclient extension has provided classes that are called auth clients. auth clients are available for many popular services like Facebook, Twitter, Google and many others to implement service-specific functionality. You can see the full list of available auth clients Here. If your desired auth client is not listed then you can create your own custom client as well.

I will use auth client for Facebook to demonstrate yii2-authclient extension usage with the advanced template of Yii2 framework.

Facebook App

First of all, you need to have a Facebook web app in order to use its service. If you already have created a Facebook app and know how to use it with other applications then you can skip this section, otherwise read on.

To create a new Facebook app go to developers.facebook.com, you will find an option to Add a new app from the top menu. Using that option add a new app for website platform.

Facebook app platform

After creating the app, you will be taken to the dashboard of your app where you can see your App ID and App Secret. We will use these in our configuration later.

Facebook app dashboard

Lastly, you need to add platform where you are intending to use this app. You can do so by clicking on Settings from left side menu and then on Add Platform button and select Website as a platform. After that, it will ask you your Site URL. This is the URL of your application site that you want to use to connect with Facebook for authentication. Enter URL of your site and click on Save Changes.

Facebook platform settings

Now your Facebook app is ready to be used for authentication purposes in you application site.

Yii2-authclient Extension Installation

yii2-authclient extension is not provided by default. You need to install it by yourself. Easiest way to do it is using composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-authclient "*"

or add following line to the require section of your composer.json file.

"yiisoft/yii2-authclient": "*"

Yii2-authclient Configuration

First of all, we need to enable and configure yii2-authclient as a component in our frontend/config/main.php file like following:

'authClientCollection' => [
  'class' => 'yii\authclient\Collection',
  'clients' => [
    'facebook' => [
      'class' => 'yii\authclient\clients\Facebook',
      'authUrl' => 'https://www.facebook.com/dialog/oauth?display=popup',
      'clientId' => 'YOUR APP CLIENT ID',
      'clientSecret' => 'YOUR APP CLIENT SECRET',
      'attributeNames' => ['name', 'email', 'first_name', 'last_name'],
    ],
  ],
],

Let's go through these settings.

First of all, in class we are passing class name of auth collection.

In clients, we need to pass array of auth client classes and their configuration. In our case, we are passing auth client class for facebook.

Yii2-authclient provide default authUrl automatically for its auth client classes, but if you want to modify default URL and use custom one then you can provide authUrl as well in configuration like I did, because I wanted to add display=popup parameter as well in URL.

The two most important and required parameters in the client class configuration are clientId and clientSecret of your service app. These are App ID and App Secret of your Facebook app, so just provide those values in these configurations.

You can provide scope to tell exactly what kind of permissions you need from the user. By default in client class, scope is set to email, which means you will be able to get public profile as well as email of the user. In our case default is enough so we don't need to provide scope. You can read more about possible values for Facebook permission scope Here.

In attributeNames you can define the names of the user attributes that you want to get from Facebook. In my case I'm asking for four attributes which are covered in public profile (default) and email permissions. More information about available attributes can be found Here

Normally, authclient generates return url properly, which is later used by the external service (Facebook, Google etc.) to redirect the user after successful authentication. But sometimes I have experienced the problem that service is not redirecting to correct url. If you experience this problem, you can explicitly define absolute url to your auth action in returnUrl of client configuration. Yii2 docs

Handling Interaction

In order to handle requests and interaction between Facebook app and our application for authentication, yii2-authclient provides us a standalone action class AuthAction that we can register in any Controller. You can read more about standalone actions Here.

In order to use and configure this AuthAction in our SiteController, we need to override actions method.

public function actions() {
  return [
    'auth' => [
      'class' => 'yii\authclient\AuthAction',
      'successCallback' => [$this, 'oAuthSuccess'],
    ],
  ];
}

In this method, we are returning array of configuration for AuthAction. Most important configuration here is successCallback, in which we provide the name of the PHP callback that will be triggered once authentication is successful. I'm passing here oAuthSuccess as the callback name, but you can name it anything you want.

Now we need to create this callback as well in same Controller class.

/**
* This function will be triggered when user is successfuly authenticated using some oAuth client.
*
* @param yii\authclient\ClientInterface $client
* @return boolean|yii\web\Response
*/
public function oAuthSuccess($client) {
  // get user data from client
  $userAttributes = $client->getUserAttributes();

  // do some thing with user data. for example with $userAttributes['email']
}

After successfull authentication oAuthSuccess will be executed with an instance of yii\authclient\ClientInterface as its argument.

At this point our user is authenticated with Facebook and we have user's data as well that we are getting by calling $client->getUserAttributes(). It returns an array containing all the fields and values provided by Facebook for that specific user.

Lastly, we can use yii\authclient\widgets\AuthChoice widget to generate social media buttons. Add following code to your view file where you want to display social media buttons to user.

<?= yii\authclient\widgets\AuthChoice::widget([
     'baseAuthUrl' => ['site/auth']
]) ?>

authUrl above should be the url to auth action that we defined in SiteController. Above code will generate social media links with proper urls for you.

Under the Hood

Yii2-authclient automatically handles OAuth interaction for you. But if you are intersted to know about what exactly is going on under the hood and how Yii2-authclient handles interaction with OAuth service, then I hope following flow diagram will help you to understand it.

OAuth 2 Interaction


30 September, 2016 update: Added information about scope, attributeNames and returnUrl parameters for Facebook client in authclient configuration section.


  Yii2, PHP