📜 ⬆️ ⬇️

HybridAuth - website integration with social networks

Introduction


On my website in php, I recently used the Loginza service to authenticate users. Everything was very cool and convenient, but the idea of ​​abandoning this wonderful service began to form in my head and that is why:

  1. Authorization of users in case of Loginza closure or rejection of it - in this case we will lose users whose linked profiles do not have email;
  2. Additional information, for example, VKontakte can give a photo of the user in several forms, including a square avatar. With Loginza it is not possible to get this data, the service itself decides which data to request and which to give;
  3. Since the sale to Yandex, Loginza has begun to die: no one responds to user requests, the service does not develop, but is in the form it was 1-2 years ago.

The question of replacement arose and the use of alternative services of desire did not arise - no one had the opportunity to “communicate” with social services. network directly, and extended profile fields are usually included in paid services. I wanted a standalone solution with the ability to flexibly customize the requested fields and in the end I settled on the HybridAuth php library.

HybridAuth


HybridAuth is an open source library that allows authorization using OAuth1, OAuth2 and OpenID. As part of the library are already setting for most of the popular social. networks like Google, Facebook, Twitter, and even VKontakte. The current stable version is 2.0.11, the version in development is 2.1.0 - there are links to github at the end of the article. It is distributed under the MIT and GPL licenses, more about this can be found here .

The library includes examples of use and a set of the most popular authorization services. Consider an example of authorization via Twitter, for this we take the latest stable version and install it on a local server. All examples are in the examples directory, service settings in hybridauth/config.php , install.php is there, which will help us create the settings file automatically, open it:
')


First we need to specify the Endpoint URL - the full path to the root directory of the plugin, it is used by some services to return to your site. Next are the settings of all authorization services, as well as instructions for obtaining ID and Secret:



For our example, create an application on Twitter. After that, we will add them to the settings of our library and save. Now let's look at an example of authorization, let's create a test.php file in the root of the site:

 <?php session_start(); $config = dirname(__FILE__) . '/hybridauth/config.php'; require_once( "hybridauth/Hybrid/Auth.php" ); if( isset( $_GET["login"] ) ) { try { $hybridauth = new Hybrid_Auth( $config ); $adapter = $hybridauth->authenticate( "twitter" ); $user_profile = $adapter->getUserProfile(); } catch( Exception $e ) { die( "<b>got an error!</b> " . $e->getMessage() ); } } if( ! isset( $user_profile ) ) { ?> <p>   .</p> <h2><a href ="test.php?login=1"></a></h2> <?php } else { ?> <fieldset> <legend>twitter </legend> <b> <?php echo $user_profile->displayName; ?></b> <hr /> <b>Hybridauth access tokens for twitter:</b> <pre><?php print_r( $adapter->getAccessToken() ); ?></pre> </fieldset> <?php } ?> 

Consider what he does:
  1. The login parameter checks the GET parameter; if it does not exist, it opens the page with the authorization proposal;
  2. When clicking on the link mysite.ru/twitter.php?login=1 we start the authorization process. An instance of the Hybrid_Auth class is created and the name of the service through which we want to log in is transmitted using the authenticate method;
  3. Facebook opens with an offer of authorization, if the user gives access, the getUserProfile method will return its profile data to us, otherwise we will get an error.

Everything is very simple! Now, let's see what kind of data getUserProfile receives in the case of Twitter. To do this, open the directory hybridauth/Hybrid/Providers , where the settings of the authorization services are stored as files, we need Twitter.php . Find the getUserProfile method and see the resulting data:

 $this->user->profile->identifier = (property_exists($response,'id'))?$response->id:""; $this->user->profile->displayName = (property_exists($response,'screen_name'))?$response->screen_name:""; $this->user->profile->description = (property_exists($response,'description'))?$response->description:""; $this->user->profile->firstName = (property_exists($response,'name'))?$response->name:""; $this->user->profile->photoURL = (property_exists($response,'profile_image_url'))?$response->profile_image_url:""; $this->user->profile->profileURL = (property_exists($response,'screen_name'))?("http://twitter.com/".$response->screen_name):""; $this->user->profile->webSiteURL = (property_exists($response,'url'))?$response->url:""; $this->user->profile->region = (property_exists($response,'location'))?$response->location:""; 

You can change any data or add your own, as well as in this file methods of getting contacts of the profile and changing the status are implemented. That is, if necessary, for any social network you can not only change the set of necessary data, but also add your own functionality based on their API.

Yandex


As an example of adding a new authorization service, let's try adding Yandex, for this we will create hybridauth/Hybrid/Providers/Yandex.php . Yandex uses OAuth2 for authorization, so our class will inherit it:

 class Hybrid_Providers_Yandex extends Hybrid_Provider_Model_OAuth2 

For OAuth1, use Hybrid_Provider_Model_OAuth1 , and for OpenID, Hybrid_Provider_Model_OpenID . Now we need to figure out what data Yandex needs to authorize the user and access his profile data. First, create a Yandex API application, to get ID and Secret fields - go here and register a new application. To get the profile data, we will use the API Login.Yandex, where we will mark the mailbox fields and the user's full name.

Example of filling data

We have the necessary keys, it remains to add them to the HybridAuth settings, open hybridauth/config.php and add to the end:

 "Yandex" => array ( "enabled" => true, "keys" => array ( "id" => "Id ", "secret" => " " ) ), 

Next, we read the Yandex documentation and see that for authorization we need to refer to oauth.yandex.ru/authorize oauth.yandex.ru/authorize , and to get a token to oauth.yandex.ru/token oauth.yandex.ru/token . It remains to find out the address of the API Login. Yandex - for this we open the API documentation and find the Login through Yandex, and there OAuth + Yandex.Login . Here we find that to obtain information about the user need to contact login.yandex.ru/info login.yandex.ru/info . Great, we have everything we need, go back to Yandex.php, in the function initialize we specify links to the API:

 $this->api->api_base_url = "https://login.yandex.ru/info"; $this->api->authorize_url = "https://oauth.yandex.ru/authorize"; $this->api->token_url = "https://oauth.yandex.ru/token"; 

We also indicate that the received token must be passed with the oauth_token parameter:

 $this->api->sign_token_name = "oauth_token"; 

Now, in the getProfiles function, we will write data parsing, to begin with, we will form a request for a profile:

 $response = $this->api->api( "?format=json" ); 

Now we have an object $ response, which contains all the data, save them by analogy with Twitter.php:

 $this->user->profile->identifier = (property_exists($response,'id'))?$response->id:""; $this->user->profile->firstName = (property_exists($response,'real_name'))?$response->real_name:""; $this->user->profile->displayName = (property_exists($response,'display_name'))?$response->display_name:""; $this->user->profile->photoURL = 'http://upics.yandex.net/'. $this->user->profile->identifier .'/normal'; $this->user->profile->gender = (property_exists($response,'sex'))?$response->sex:""; $this->user->profile->email = (property_exists($response,'default_email'))?$response->default_email:""; $this->user->profile->emailVerified = (property_exists($response,'default_email'))?$response->default_email:""; 

As a result, we got this file:
Yandex.php
 <?php class Hybrid_Providers_Yandex extends Hybrid_Provider_Model_OAuth2 { function initialize() { parent::initialize(); $this->api->api_base_url = "https://login.yandex.ru/info"; $this->api->authorize_url = "https://oauth.yandex.ru/authorize"; $this->api->token_url = "https://oauth.yandex.ru/token"; $this->api->sign_token_name = "oauth_token"; } function getUserProfile() { $response = $this->api->api( "?format=json" ); if ( !isset( $response->id ) ) { throw new Exception( "User profile request failed! {$this->providerId} returned an invalide response.", 6 ); } $this->user->profile->identifier = (property_exists($response,'id'))?$response->id:""; $this->user->profile->firstName = (property_exists($response,'real_name'))?$response->real_name:""; $this->user->profile->displayName = (property_exists($response,'display_name'))?$response->display_name:""; $this->user->profile->photoURL = 'http://upics.yandex.net/'. $this->user->profile->identifier .'/normal'; $this->user->profile->gender = (property_exists($response,'sex'))?$response->sex:""; $this->user->profile->email = (property_exists($response,'default_email'))?$response->default_email:""; $this->user->profile->emailVerified = (property_exists($response,'default_email'))?$response->default_email:""; return $this->user->profile; } } ?> 


Let's change our example from Twitter to Yandex:

 $adapter = $hybridauth->authenticate( "yandex" ); 

Trying to log in:



And in the end we get:



That's all, authorization through Yandex was successful. You can do the rest of the services that we need.

Convenient connection, simple addition of new services and open source code - everything that was lacking when working with third-party services. Also, to simplify integration, the library has plug-ins to popular frameworks and CMS, such as Yii, Symfony2, Wordpress, Drupal and others .

For errors and inaccuracies, as well as with additions, please contact the PM.

Related Links:

upd : laid out authorization for Yandex and Mail.ru , Odnoklassniki turned out with a crutch for compatibility with PHP> 5.3.0.

Source: https://habr.com/ru/post/149187/


All Articles