Integrating Open Authentication using Opauth

Share this article

Open Authentication has evolved as a standard for third-party authentication in recent years and allows us to securely authenticate our application’s users through a standard interface. Twitter and Facebook has been the standouts among dozens of authentication service providers. And of course we can find many open source libraries for accessing authentication providers, but a large problem with these libraries is that different developers have different styles and ways of implementing the same system. It’s difficult to use these libraries in a standard way or to replace one library with another.

Opauth is an open source library created to standardize the authentication process among various service providers. In this article we’ll explore how we can effectively use Opauth to standardize our authentication strategies. I’ll be using CodeIgniter here, but even if you’re not familiar with CodeIgniter, I suggest you continue reading since it will be similar for other frameworks as well. Once you understand the necessary details for integration, adapting to any framework is super simple.

Importance of Opauth

Opauth acts as an interface between your application and the open authentication provider libraries. It can be considered as a standard adapter for these authentication libraries. Once you setup Opauth, any service can be requested using a standard set of methods instead of learning various different APIs. It also allows us to receive responses for successful or failed executions in a standard format. Opauth is highly portable, giving us the ability to change open auth service libraries as well as our PHP framework of choice with minor modifications.

Opauth Execution Process

First, let’s look at the following illustration which shows the process of handling application requests by Opauth:

opauth-01

Initially the application requests open authentication details from the CodeIgniter library. The library initializes the Opauth process by creating an Opauth class object. Opauth requests the standard strategy depending on the provided URL. A strategy is a set of instructions that talk to the auth providers and handle their responses. The strategy employs a specific library to initiate the actual authentication request. Finally we have access to the respective API of the service provider.

As you can see in the image, I have separated the Opauth section. Opauth contains the initialization, service provider libraries, and the respective strategy interfaces. The actual authentication request starts after the process is completed by Opauth of standardizing the request.

There are around 18 libraries currently listed on the Opauth site, which comes with a built-in strategy class for Opauth. In cases where a service provider doesn’t have a strategy class, we can create our own class using the strategy contribution guide.

Integrating Opauth with CodeIgniter

Opauth integration libraries are available for use with many of the more popular frameworks, but also a plain “vanilla” version of the library to be used in those which don’t use a framework. Ideally you should have an idea of how to integrate the plain PHP version into a framework so you can work with those which are not supported at the moment. CodeIgniter is one of my favorites, so I’ll explain how you can integrate the plain Opauth version into CodeIgniter from scratch.

First, we have to download the plain version of the Opauth library from GitHub and copy the downloaded directory to your application/libraries directory (since we’re using Codeigniter, it needs to be integrated as a plugin or library). I’ve named the directory Opauth_lib, and you can remove both the example and test directories inside if necessary.

I’d like to show you how to integrate Opauth into CodeIgniter using a custom Codeigniter library, so create the library file as Opauth_lib.php and require the Opauth.php file located inside the lib directory.

<?php
$opauth_lib_dir = dirname(__FILE__) . '/Opauth_lib/lib/Opauth/';
require $opauth_lib_dir . 'Opauth.php';

Now create the class for the library.

<?php
class OpauthLib
{
    protected $configurations;
    protected $opauth_obj;

    public function __construct($configurations) {
        $this->configurations = $configurations;
    }
}

Configuration is necessary for making Opauth work, so I’ve passed the configuration data into the constructor of the library class. I like to use a config file inside the application/config directory to include the necessary information for Opauth as shown here:

<?php
$config['opauth'] = array(  
    'path' => '/auth/login/',
    'callback_url' => 'http://example.com/auth/authenticate/',
    'callback_transport' => 'post',
    'security_salt' => 'rakhithanimesh123',

    'Strategy' => array(
        'Twitter' => array(
            'key' => 'twitter app key',
            'secret' => 'twitter app secret'
        ),
        'LinkedIn' => array(
            'api_key' => 'linkedin app key',
            'secret_key' => 'linkedin app secret'
        )
    ),
);

Let’s discuss the meaning of each of the parameters in the above code.

  • path – defines where you access your login links. Since I have installed Codeigniter as the root directory, the path will be /auth/login/, which is the controller and function name respectively.
  • callback_url – defines the URL where you handle the response after successful authentication or a failure. I’ve used same controller but with a different function. Here we have to define the complete URL instead of a relative URL.
  • callback_transport – defines how you handle the response. It defaults to “session”. Since CodeIgniter doesn’t use native sessions, I’ve specified “post” for the callback transport. You can use “session”, “get”, or “post” for this parameter.
  • security_salt – defines a random security key for signing the oauth response.
  • Strategy – defines an array of service provider information for your application. We need to provide the necessary parameters with their values for each of strategy. Here I have used Twitter and LinkedIn as the strategies and their application keys as parameters.

Once the strategies are defined in the config, we have to get the respective libraries with their strategy class and copy them to the OpauthLib/lib/Opauth/Strategy directory. Service providers are called vendors in Opauth, and the following screen shows the contents inside a specific strategy.

opauth-2

Implementing an Open Authentication Login

Now that we’ve integrated with CodeIgniter, the next step is to create the login links for each of the strategies we defined in the config file. I’ve used the path /auth/login and so we need to create a controller with a login() method.

<?php
class Auth extends CI_Controller
{
    protected $open_auth_config;

    public function __construct() {
        parent::__construct();
        $this->open_auth_config = $this->config->item('opauth');
        $this->load->library('opauth_lib', $this->open_auth_config);
    }

    public function login($stratergy = "") {
        if ($stratergy != "") {
            $this->opauth_lib->initialize();
        }
        else {
            foreach ($this->open_auth_config['Strategy'] as $strategy => $strategy_detail) {
                echo "<p><a href='".$this->config->item('base_url')."auth/login/".strtolower($strategy)."'>".$strategy."</a></p>";
            }
        }
    }
}

The constructor receives the Opauth configuration information and loads the library we created in the previous section. The login() method creates the login links to redirect the user to the respective site for authentication. Opauth login URLs are configured by adding the strategy into the path parameter. For example, the Twitter login URL will be /auth/login/twitter and LinkedIn URL will be /auth/login/linkedin.

The strategy is passed as an optional parameter to our login() method. Therefore, when the strategy is empty, we generate login links for all the strategies using the Opauth config. When the user clicks on a login link, the strategy will not be empty and we call the initialize method of our Opauth library to redirect the user for authentication. The Following is the implementation for the initialize method inside the library class Opauth_lib.

<?php
public function initialize() {
    $this->opauth_obj = new Opauth($this->configurations);
    $this->opauth_obj->run();
}

All it needs to do is initialize the Opauth class in the core Opauth library with the configurations and call the run() method. It will automatically identify the requested strategy through the URL and redirect the user for authentication.

Handling the Open Auth Response

Let’s assume that the user clicked the Twitter login link. Once she authorizes the application by logging into Twitter, redirection will be take the user back to the location we specified as the callback URL in the config. In this case, the response will be handled through Auth‘s authenticate() method. Here’s its implementation:

<?php
public function authenticate() {
    $response = null;
    $response = unserialize(base64_decode($_POST['opauth']));
    echo "<pre>";print_r($response);exit;
}

Since I specified the post method in the config, the response can be accessed using $_POST['opauth']. Now the user has logged into our system using open authentication and the response will contain user details, user tokens, and other necessary information in a standard format. You can save the desired information in a session or database to keep the login active for the user across many requests.

To implement a logout method, simply clear out the respective information used to keep the user signed in and redirect back to the login links.

In Closing

In this article we discussed how to integrate Opauth with CodeIgniter. The following is a general list of guidelines for integrating Opauth with any given PHP framework:

  1. Download the plain version of Opauth and create a library or plugin depending on your framework.
  2. Create a new config file or copy the config details to existing config file of the framework.
  3. Add any number of strategies with the required parameters.
  4. Get the service provider libraries for each of the defined strategies and copy to the libraries’ directories inside Opauth.
  5. Create two functions for handling login links and responses for available strategies.
  6. Initialize the Opauth class and call its run() method to get things working.

You can grab a copy of the source code used for this article from GitHub.

Let me know what you think about using Opauth to standardize your authentication mechanism. Try to create Opauth plugins for other PHP frameworks and support the open source community.

Image via Fotolia

Rakhitha NimeshRakhitha Nimesh
View Author

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on Building Impressive Presentations with Impress.js. He is a regular contributor to 1stWebDesigner, Tuts+ network and SitePoint network. Make sure to follow him on Google+.

Advanced
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week