Many modern websites allow users to log in through their social network accounts. For example, the SitePoint community allows users to log in with their Facebook, Twitter, Google, Yahoo, or GitHub accounts without registering for a new account.
This tutorial will introduce HybridAuth - a PHP library that simplifies the construction of social login capabilities.
HybridAuth acts as an abstract API between applications and various social APIs and identity providers.
Key Points
Installation
Composer is recommended to install HybridAuth. We will also use Slim as the basis for the sample application.
<code>{ "require": { "slim/slim": "2.*", "hybridauth/hybridauth": "2.3.0" } }</code>
Social login with HybridAuth
To use HybridAuth, copy the /vendor/hybridauth/hybridauth/hybridauth
and config.php
(HybridAuth endpoint files) in the index.php
folder to your project root folder.
Rename the index.php
file to hybrid.php
because index.php
will be used by the Slim framework for our demo application logic.
Fill the config.php
file with your app (e.g. Facebook, Twitter app) credentials.
For example, if you want users to log into your website via Facebook, Google, and Twitter; your profile should look like this. My application URL is http://slim.local
.
<code>return [ "base_url" => "http://slim.local/", "providers" => [ "Google" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], ], "Facebook" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], "trustForwarded" => false ], "Twitter" => [ "enabled" => true, "keys" => [ "key" => "", "secret" => "" ] ], ], "debug_mode" => true, "debug_file" => "bug.txt", ];</code>
Note: The base_url
parameter must point to the HybridAuth endpoint file, in this case hybrid.php
.
Refer to the HybridAuth configuration documentation for more information.
Next, load the vendor autoloader and instantiate the class.
<code>require 'vendor/autoload.php'; $hybridauth = new Hybrid_Auth( 'config.php' );</code>
Use the authenticate
method to authenticate the user using the given provider.
For Facebook:
<code>$adapter = $hybridauth->authenticate( "Facebook" );</code>
For Twitter:
<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
For Google:
<code>$adapter = $hybridauth->authenticate( "Google" );</code>
must match the provider array key in the authenticate()
file. config.php
After authentication, use the
method to retrieve the user's profile data. getUserProfile()
<code>{ "require": { "slim/slim": "2.*", "hybridauth/hybridauth": "2.3.0" } }</code>
variable will be an object that contains the returned user profile data. $user_profile
file from GitHub.php
to a location in the application (in this case the provider directory). Load the file using a provider wrapper, where vendor/hybridauth/hybridauth/additional-providers/hybridauth-github/Providers
is the path to the GitHub file and path
is the name of its PHP class. class
<code>return [ "base_url" => "http://slim.local/", "providers" => [ "Google" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], ], "Facebook" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], "trustForwarded" => false ], "Twitter" => [ "enabled" => true, "keys" => [ "key" => "", "secret" => "" ] ], ], "debug_mode" => true, "debug_file" => "bug.txt", ];</code>
method of HybridAuth to authenticate users using GitHub, as shown below: authenticate()
<code>require 'vendor/autoload.php'; $hybridauth = new Hybrid_Auth( 'config.php' );</code>
Social login implementation
Usually, every website with a login and registration system uses the user's email address or username to identify and log in to their account. If you plan to implement social login, it is recommended not to use the user's username or email for authentication.One of the reasons to object to this practice is that, for example, Twitter does not return the user's email address that has been authenticated through it. That is, the returned profile data does not contain the user's email.
Most, if not all, social providers, such as Facebook, Twitter, Google, LinkedIn and even GitHub, return a unique user ID number after authorization.
Do not log in to the user's account using the user's email, but use the identifier returned by the social provider, as shown below: Create a user account if the user does not have an account; log in if the user has an account Go to the website.
Writing a demo application
We will use the Slim PHP framework to build a simple web application to demonstrate practical examples of how to implement a social login using HybridAuth.I assume you have HybridAuth and Slim frameworks installed. Otherwise, refer to the installation guide above.
Application Structure
<code>$adapter = $hybridauth->authenticate( "Facebook" );</code>
<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
The file namespace is Model, followed by the class definition and constructor.
<code>$adapter = $hybridauth->authenticate( "Google" );</code>
Method Returns true if the identifier (user identification number) already exists in the database, otherwise returns false. identifier_exists
<code>$user_profile = $adapter->getUserProfile();</code>
Method Insert user profile data into the database. register_user
<code>"Github" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], "wrapper" => [ "path" => "providers/GitHub.php", "class" => "Hybrid_Providers_GitHub" ] ]</code>
method adds the created user session to the HybridAuth session when called (created after the provider successfully authorizes the user). login_user
<code>$adapter = $hybridauth->authenticate( "Github" );</code>
Method Delete or destroy a user's session when clicking the logout link. logout_user
<code>|-scr/ |----App_Model.php |-templates/ |----login.php |----welcome.php |-vendor/ |-composer.json |-config.php |-hybrid.php |-index.php |-.htaccess</code>
<code>{ "require": { "slim/slim": "2.*", "hybridauth/hybridauth": "2.3.0" } }</code>
Register PSR-4 autoloader for the Model class by adding the following code to your composer.json file.
<code>return [ "base_url" => "http://slim.local/", "providers" => [ "Google" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], ], "Facebook" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], "trustForwarded" => false ], "Twitter" => [ "enabled" => true, "keys" => [ "key" => "", "secret" => "" ] ], ], "debug_mode" => true, "debug_file" => "bug.txt", ];</code>
Run composer dump-autoload
to regenerate the vendor/autoload.php
file.
Load composer in application index.php
file automatically loads the file and instantiates Slim.
<code>require 'vendor/autoload.php'; $hybridauth = new Hybrid_Auth( 'config.php' );</code>
Create a directory called templates to store all template files, and then register or configure it in Slim as follows:
<code>$adapter = $hybridauth->authenticate( "Facebook" );</code>
Create a Slim database singleton resource that will return the database connection instance when called.
<code>$adapter = $hybridauth->authenticate( "Twitter" );</code>
Another singleton resource that returns a HybridAuth instance is also created.
<code>$adapter = $hybridauth->authenticate( "Google" );</code>
Instantiate the application model class by passing a database connection as a parameter.
<code>$user_profile = $adapter->getUserProfile();</code>
The following authenticate
function when added as a parameter to the route, if the user is not logged in, it will redirect it to the login page.
<code>"Github" => [ "enabled" => true, "keys" => [ "id" => "", "secret" => "" ], "wrapper" => [ "path" => "providers/GitHub.php", "class" => "Hybrid_Providers_GitHub" ] ]</code>
Redirects the logged out user to the login page when he accesses the app's home page or index page.
<code>$adapter = $hybridauth->authenticate( "Github" );</code>
The following is the routing definition for social login links. That is, when the link http://slim.local/login/facebook
is clicked, HybridAuth redirects the user to Facebook for authorization. The same goes for Twitter http://slim.local/login/twitter
, Google http://slim.local/login/google
and all other supported providers.
<code>|-scr/ |----App_Model.php |-templates/ |----login.php |----welcome.php |-vendor/ |-composer.json |-config.php |-hybrid.php |-index.php |-.htaccess</code>
Calling the authenticate()
method of HybridAuth redirects the user to the given social provider.
After successful authorization, the $user_profile
variable will populate the user profile data.
Call the identifier_exists()
method to check whether the user identifier exists in the database. If true, the user logs into the website. Otherwise, an account is created for the user and the user is logged in.
This is the code to log out the route.
CREATE TABLE IF NOT EXISTS `users` ( `id` int(10) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id), `identifier` varchar(50) NOT NULL, UNIQUE KEY `identifier` (`identifier`), `email` varchar(50) DEFAULT NULL, `first_name` varchar(20) DEFAULT NULL, `last_name` varchar(20) DEFAULT NULL, `avatar_url` varchar(255) ) ENGINE=InnoDB;
The logout_user
method we have discussed in the model class is called to destroy the user session, and also to log out of the user's connection provider. Hybrid_Auth::logoutAllProviders()
<?php namespace Model; class App_Model { /** @var object Database connection */ private $conn; /** * Instantiate the model class. * * @param object $db_connection DB connection */ public function __construct(\PDO $db_connection) { $this->conn = $db_connection; } // ... rest of the methods ... }
/** * Check if a HybridAuth identifier already exists in DB * * @param int $identifier * * @return bool */ public function identifier_exists($identifier) { try { $sql = 'SELECT identifier FROM users'; $query = $this->conn->query($sql); $result = $query->fetchAll(\PDO::FETCH_COLUMN, 0); return in_array($identifier, $result); } catch ( \PDOException $e ) { die( $e->getMessage() ); } }
Conclusion
In this article, we learned how to integrate social login capabilities with websites using the powerful and robust HybridAuth PHP library.If you have any questions or contributions, please let us know in the comments.
FAQ (FAQ) for social login with PHP and HybridAuth
HybridAuth is a popular open source social login PHP library. It allows web developers to easily build social applications by providing an easy way to authenticate users through their social media accounts. HybridAuth acts as an abstract API between applications and various social APIs and identity providers such as Facebook, Twitter, and Google. It works by integrating with existing login systems in PHP applications and adding social login capabilities.
HybridAuth can be installed through Composer (the dependency management tool in PHP). After installation, you need to configure it by setting up the provider you want to use (social network). Each provider requires a unique set of parameters, such as keys and keys, which you can obtain by creating applications on the developer platforms of each social network.
HybridAuth is very secure because it uses OAuth, an open access delegate standard. OAuth provides secure designated access, meaning that users can grant websites permission to access their information on other websites without providing them with a password. This makes HybridAuth a secure option for social login.
Yes, HybridAuth can be used on multiple websites. You just need to use the correct callback URL configuration library for each website. This makes it a flexible solution for developers who manage multiple websites.
HybridAuth has a built-in error handling system. When an error occurs, it throws an exception that you can catch and handle based on your application's error handling policy. This makes debugging and fixing issues easier.
Yes, you can customize the look and style of the social login button. HybridAuth offers social login capabilities, but the design and layout of the buttons are entirely up to you.
Updating HybridAuth is as easy as running a command in Composer. This ensures that you always have the latest version with all security patches and updates.
Yes, HybridAuth is not a framework and can be used with any PHP framework. This makes it a versatile choice for developers using different PHP frameworks.
Testing social login locally can be tricky because social networks require valid callback URLs. However, you can expose your local server to the internet using tools such as ngrok and use that URL as a callback URL.
No, HybridAuth is designed for social login. For traditional email and password authentication, you need to use other PHP libraries or build your own authentication system.
The output maintains the original image formatting and placement. The text has been paraphrased and reorganized to improve flow and readability while preserving the original meaning. The code examples remain unchanged.
The above is the detailed content of Social Logins in PHP with HybridAuth. For more information, please follow other related articles on the PHP Chinese website!