Hybridauth is a quite popular library to integrate Social Login in PHP based applications including CodeIgniter. You can add the login/register feature from almost all social providers like Google, Facebook using it. Hybridauth 3 has a lot of improvements to integrate social Sign In/Up in PHP websites.
However, the latest HA has a lack of proper documentation and support. Additionally, not enough plugins are available yet for frameworks like CodeIgniter, CakePHP. So I decided to write this article to simplify the implementation of all in one social login in CI3 using Hybridauth 3.
Create Apps and Projects for Social Login
We will write common code for social providers like Google and Facebook using the Hybridauth library. The code will interact with the library and make the social login in the CodeIgniter website easier.
Before you begin, it is a must to create an app or project for each provider you want to use. For this, visit the given provider’s interface and set up that. If you haven’t done so far then refer articles:
After all, just remember that our endpoint URL is http://localhost/tuts/social/auth/ for the development environment. Similarly, it would be DOMAIN/social/auth/ for the live website. Just replace DOMAIN with your real domain name along with the protocol and with or without www.
Also, the trailing slash is a must. Don’t forget to supply it to the respective field by the provider. If the directory in the htdocs folder is anything other then ‘tuts’ then update the endpoint URL wherever applicable.
Integrate Hybridauth 3 in CodeIgniter 3
So far I assume you have a running CI3 project in the local setup. Now we need to download and add the HA library in our project. But DON’T DOWNLOAD the latest release of it from GitHub. Because you won’t find autoloader file in that after unzipping.
Rather download the master zip from this link:
https://github.com/hybridauth/hybridauth/archive/master.zip
Further, extract the zip in application/third_party directory. So the autoloader file path could look as:
CodeIgniter Function for Social Login
Here is the magic code, that works as all in one unified interface. Add in the social.php controller file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); //Include Hybridauth autoloader require APPPATH . '/third_party/hybridauth/autoload.php'; //Import Hybridauth's namespace use Hybridauth\Hybridauth; class Social extends CI_Controller { function __construct() { parent::__construct(); //Load URL helper $this->load->helper('url'); //Load session library $this->load->library('session'); } //Displays social login links function index() { //Instantiate Hybridauth's classes $hybrid = new Hybridauth($this->getHybridConfig()); //Get enabled providers array $providers = $hybrid->getProviders(); //List a link to login foreach ($providers as $provider) { $href = sprintf(base_url('%s/auth/%s/') , strtolower($this->router->fetch_class()) , $provider); printf('<p><a href="%s">Login with %s</p>', $href, $provider); } } //Processes social login function auth($provider = NULL) { $service = NULL; try { //Instantiate Hybridauth's classes $hybrid = new Hybridauth($this->getHybridConfig()); //Check if given provider is enabled if ((isset($provider)) && in_array($provider, $hybrid->getProviders())) { $this->session->set_userdata('provider', $provider); } //Update variable with the valid provider $provider = $this->session->userdata('provider'); if ($provider) { $service = $hybrid->authenticate($provider); if ($service->isConnected()) { //Get user profile $profile = $service->getUserProfile(); //Get user contacts $contacts = $service->getUserContacts(); /* Disconnect the service else HA would reuse stored session data rather making a fresh request in case the user has denied permissions in the previous authorization request */ $service->disconnect(); $this->session->unset_userdata('provider'); //Display the profile data echo 'Name: ' . $profile->displayName; print_r($profile); } else { $this->session->set_flashdata('showmsg', array('msg' => 'Sorry! We couldn\'t authenticate your identity.')); } } } catch(Exception $e) { if (isset($service) && $service->isConnected()) $service->disconnect(); $error = 'Sorry! We couldn\'t authenticate you.'; $this->session->set_flashdata('showmsg', array('msg' => $error)); $error .= '\nError Code: ' . $e->getCode(); $error .= '\nError Message: ' . $e->getMessage(); log_message('error', $error); } //redirect(); } //Hybridauth configuration private function getHybridConfig() { $config = array( 'callback' => site_url('social/auth/') , 'providers' => array( 'Google' => array( 'enabled' => true, 'keys' => array( 'id' => 'YOUR_CLIENT_ID', 'secret' => 'YOUR_CLIENT_SECRET' ) , 'scope' => 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile' ) , 'Facebook' => array( 'enabled' => true, 'keys' => array( 'id' => (ENVIRONMENT == 'development') ? 'DEVELOPMENT_APP_ID' : 'PRODUCTION_APP_ID', 'secret' => (ENVIRONMENT == 'development') ? 'DEVELOPMENT_APP_SECRET' : 'PRODUCTION_APP_SECRET' ) , 'scope' => 'email, public_profile' ) , 'Twitter' => array( 'enabled' => true, 'keys' => array( 'key' => 'APP_KEY', 'secret' => 'APP_SECRET' ) ) ) , 'hybrid_debug' => array( 'debug_mode' => 'info', /* none, debug, info, error */ 'debug_file' => APPPATH . '/logs/log-' . date('Y-m-d') . '.php' ) ); return $config; } } |
In the controller, we’ve included HA autoloader file and further used Hybridauth’s namespace. Then there are three methods. The index method displays a social link with each enabled provider. In the auth method, the HA library handles all the processes. Finally, the last one is a private method containing the HA configuration array.
The code is self-explanatory and straight forward. I’ve mentioned adequate comments as well. Still, if you face any trouble, you’re welcome to ask through the form at the bottom. Now it’s time to test. Access the URL http://localhost/social/ in the browser and check by logging in through any network.
Add Routing Rule to Handle Response
This step is completely optional and only if you’re unable to catch the response. Add one line routing rule to handle the provider’s response in CodeIgniter. Since it requires to pass the last URI segment as a parameter instead of the method name. Open the file routes.php from the application/config directory and add the rule:
1 | $route['auth/(.+)'] = 'social/auth/$1'; |
Now give it a try. All should work fine.
Social Sign In/Up Provider Challenges
Till now you haven’t to worry about any individual social provider. However, technically there are more complexions involved. For example, not all the providers return you the email address. However, each authenticated user has an ID field for sure in the profile response.
Further, the JSON data returned might not have exact same keys. Like, the ID key name can be either id or identifier or something else. So you need to take proper care of it.
Additionally, you need more steps to resend an authorization request that has a permission denied response previously. Otherwise, providers like Facebook and Google will treat it as a policy violation. As a result, you might be barred from using their social login service.
I leave all these challenges on you. What I can hint is you need to pass extra parameters in authorize_url_parameters for Hybridauth. For a reference. check links at the bottom for relevant external resources.
If you need our professional services to manage social Sign In/Up, don’t forget to drop an email to contact@astech.solutions.
All in One Social Login – HA & CI
So hope you have understood the fundamental concept to add all social login in CodeIgniter 3 websites. And you have also seen that it is much easier using Hybridauth 3. Also, you haven’t the need to deal with each provider-specific API or SDK.
In the next article, I would love to teach how to set up a complete social login system using the database. Until stay in touch and don’t forget to leave the feedback. Also, share the article if you like it.
Finally, be careful, stay at home, and keep you as well as your loved once safer from the coronavirus (at the time of writing this article, it is epidemic).
Reference:
This code is with codegnetor 3, how to do initialization in latest version of ci4
I was able to authenticate using your script, so thank you for that.
One question: after being succesfully authenticated I get redirected to one of the authorized redirect URIs I configured in Google.
That’s perfect. But how do I check on any page that there was a succesful OAuth login?
Or I could have asked the question differently;
The code after $service = $hybrid->authenticate($provider) in function auth() is not reached, because of the redirect. I guess it should (otherwise the code there does not make any sense), but what am I doing wrong than?
Thank you for your time.
Hello Robert,
As I could understand from your comment, you want to check on other pages if the visitor has a successful OAuth login.
I would suggest you set a session variable containing relevant OAuth response data upon successful login after line #76 in the code. And delete the variable on some other event like a logout within your website.
Line #60 is always reached as long as there is the provider variable set. It’s just Hybridauth that either parses the response or redirects to the provider’s login page if a response is absent.
too many redirect issues, can you please give me
Hi Jayesh,
The issue is with your routing rules and setup. I suggest you add try each method one by one.
Amazing explanation. I had spend 2days for this, and it took 10min to understand from you.
Thank you so much for your very good example.
awesome.. what a implementation
I visited a few sites and all were charging $30 to download the code thank you soo much for brilliant explanation.