This commit is contained in:
Jaybe
2025-03-05 14:10:06 +09:00
commit 7a77932344
1905 changed files with 122510 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
Hybridauth 3 Examples
======================
File | Description
-------------- | ------------------------------------------------------------------------------
example_01.php | This simple example illustrate how to authenticate users with GitHub. If you're new to Hybridauth, this file is the one you'll likely want to check.
example_02.php | Details how to use users in a similar fashion to Hybridauth 2. Note that while Hybridauth 3 provides a similar interface to Hybridauth 2, both versions are not fully compatible with each other.
example_03.php | An example on how use Access Tokens to access providers APIs, and how to setup custom API endpoints.
example_04.php | A simple example that shows how to connect users to providers using OpenID.
example_05.php | A simple example that shows how to use Guzzle as a Http Client for Hybridauth instead of PHP Curl extension.
example_06/ | A simple example that shows how to organize multiple providers.
example_07/ | A simple example that shows how to organize multiple providers, using a pop-up.
+187
View File
@@ -0,0 +1,187 @@
<?php
/*!
* This simple example illustrate how to authenticate users with GitHub.
*
* Most other providers work pretty much the same.
*/
/**
* Step 0: Start PHP session
*
* Normally this step is not required as Hybridauth will attempt to start the session for you, however
* in some cases it might be better to call session_start() at top of script to avoid cookie-based sessions
* issues.
*
* See: http://php.net/manual/en/function.session-start.php#refsect1-function.session-start-notes
* http://stackoverflow.com/a/8028987
*/
session_start();
/**
* Step 1: Require the Hybridauth Library
*
* Should be as simple as including Composer's autoloader.
*/
include '../src/autoload.php';
/**
* Step 2: Configuring Your Application
*
* If you're already familiar with the process, you can skip the explanation below.
*
* To get started with GitHub authentication, you need to create a new GitHub application.
*
* First, navigate to https://github.com/settings/developers then click the Register
* new application button at the top right of that page and fill in any required fields
* such as the application name, description and website.
*
* Set the Authorization callback URL to https://path/to/hybridauth/examples/example_01.php.
* Understandably, you need to replace 'path/to/hybridauth' with the real path to this script.
*
* Note that Hybridauth provides an utility function that can generate the current page url for you
* and can be used for the callback. Example: 'callback' => Hybridauth\HttpClient\Util::getCurrentUrl()
*
* After configuring your GitHub application, simple replace 'your-app-id' and 'your-app-secret'
* with your application credentials (Client ID and Client Secret).
*
* Providers who uses OAuth 2.0 protocol (i.g., GitHub, Facebook, Google, etc.) may need
* an Authorization scope as additional parameter. Authorization scopes are strings that
* enable access to particular resources, such as user data.
*
* https://developer.github.com/v3/oauth/
* https://developer.github.com/v3/oauth/#scopes
*/
$config = [
'callback' => 'https://path/to/hybridauth/examples/example_01.php', // or Hybridauth\HttpClient\Util::getCurrentUrl()
'keys' => ['id' => 'your-app-id', 'secret' => 'your-app-secret'], // Your Github application credentials
/* optional : set scope
'scope' => 'user:email', */
/* optional : set debug mode
'debug_mode' => true,
// Path to file writeable by the web server. Required if 'debug_mode' is not false
'debug_file' => __FILE__ . '.log', */
/* optional : customize Curl settings
// for more information on curl, refer to: http://www.php.net/manual/fr/function.curl-setopt.php
'curl_options' => [
// setting custom certificates
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CAINFO => '/path/to/your/certificate.crt',
// set a valid proxy ip address
CURLOPT_PROXY => '*.*.*.*:*',
// set a custom user agent
CURLOPT_USERAGENT => ''
] */
];
/**
* Step 3: Instantiate Github Adapter
*
* This example instantiates a GitHub adapter using the array $config we just built.
*/
$github = new Hybridauth\Provider\GitHub($config);
/**
* Step 4: Authenticating Users
*
* When invoked, `authenticate()` will redirect users to GitHub login page where they
* will be asked to grant access to your application. If they do, GitHub will redirect
* the users back to Authorization callback URL (i.e., this script).
*
* Note that GitHub and few other providers will ask their users for authorisation
* only once.
*/
$github->authenticate();
/**
* Step 5: Retrieve Users Profiles
*
* Calling getUserProfile returns an instance of class Hybridauth\User\Profile which contain the
* connected user's profile in simple and standardized structure across all the social APIs supported
* by Hybridauth.
*/
$userProfile = $github->getUserProfile();
echo 'Hi ' . $userProfile->displayName;
/**
* Bonus: Access GitHub API
*
* Now that the user is authenticated with Gihub, and depending on the authorization given to your
* application, you should be able to query the said API on behalf of the user.
*
* As an example we list the authenticated user's public gists.
*/
$apiResponse = $github->apiRequest('gists');
/**
* Step 6: Disconnect the adapter
*
* This will erase the current user authentication data from session, and any further
* attempt to communicate with Github API will result on an authorisation exception.
*/
$github->disconnect();
/**
* Final note: Catching Exceptions
*
* Hybridauth use exceptions extensively and it's important that these exceptions
* be properly caught/handled in your code.
*
* Below is a basic example of how to catch exceptions.
*
* Note that on the previous step we disconnected from the API; meaning Hybridauth
* has erased the oauth access token used to sign http requests from the current
* session, thus, any new request we now make will now throw an exception.
*
* It's important that you don't show Hybridauth exception's messages to the end user as
* they may include sensitive data, and that you use your own error messages instead.
*/
try {
$github->getUserProfile();
}
/**
* Catch Curl Errors
*
* This kind of error may happen in case of:
* - Internet or Network issues.
* - Your server configuration is not setup correctly.
*
* The full list of curl errors that may happen can be found at http://curl.haxx.se/libcurl/c/libcurl-errors.html
*/
catch (Hybridauth\Exception\HttpClientFailureException $e) {
echo 'Curl text error message : ' . $github->getHttpClient()->getResponseClientError();
}
/**
* Catch API Requests Errors
*
* This usually happens when requesting a:
* - Wrong URI or a mal-formatted http request.
* - Protected resource without providing a valid access token.
*/
catch (Hybridauth\Exception\HttpRequestFailedException $e) {
echo 'Raw API Response: ' . $github->getHttpClient()->getResponseBody();
}
/**
* Base PHP's exception that catches everything [else]
*/
catch (\Exception $e) {
echo 'Oops! We ran into an unknown issue: ' . $e->getMessage();
}
+75
View File
@@ -0,0 +1,75 @@
<?php
/*!
* Details how to use users in a similar fashion to Hybridauth 2. Note that while Hybridauth 3 provides
* a similar interface to Hybridauth 2, both versions are not fully compatible with each other.
*/
include '../src/autoload.php';
use Hybridauth\Hybridauth;
use Hybridauth\HttpClient;
$config = [
'callback' => HttpClient\Util::getCurrentUrl(),
'providers' => [
'GitHub' => [
'enabled' => true,
'keys' => ['id' => '', 'secret' => ''],
],
'Google' => [
'enabled' => true,
'keys' => ['id' => '', 'secret' => ''],
],
'Facebook' => [
'enabled' => true,
'keys' => ['id' => '', 'secret' => ''],
],
'Twitter' => [
'enabled' => true,
'keys' => ['key' => '', 'secret' => ''],
]
],
/* optional : set debug mode
'debug_mode' => true,
// Path to file writeable by the web server. Required if 'debug_mode' is not false
'debug_file' => __FILE__ . '.log', */
/* optional : customize Curl settings
// for more information on curl, refer to: http://www.php.net/manual/fr/function.curl-setopt.php
'curl_options' => [
// setting custom certificates
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_CAINFO => '/path/to/your/certificate.crt',
// set a valid proxy ip address
CURLOPT_PROXY => '*.*.*.*:*',
// set a custom user agent
CURLOPT_USERAGENT => ''
] */
];
try {
$hybridauth = new Hybridauth($config);
$adapter = $hybridauth->authenticate('GitHub');
// $adapter = $hybridauth->authenticate('Google');
// $adapter = $hybridauth->authenticate('Facebook');
// $adapter = $hybridauth->authenticate('Twitter');
$tokens = $adapter->getAccessToken();
$userProfile = $adapter->getUserProfile();
// print_r($tokens);
// print_r($userProfile);
$adapter->disconnect();
} catch (\Exception $e) {
echo $e->getMessage();
}
+32
View File
@@ -0,0 +1,32 @@
<?php
/*!
* An example on how use Access Tokens to access providers APIs, and how to setup custom API endpoints.
*/
include 'vendor/autoload.php';
$config = [
'callback' => Hybridauth\HttpClient\Util::getCurrentUrl(),
'keys' => ['id' => 'your-facebook-app-id', 'secret' => 'your-facebook-app-secret'],
'endpoints' => [
'api_base_url' => 'https://graph.facebook.com/v2.8/',
'authorize_url' => 'https://www.facebook.com/dialog/oauth',
'access_token_url' => 'https://graph.facebook.com/oauth/access_token',
]
];
try {
$adapter = new Hybridauth\Provider\Facebook($config);
$adapter->setAccessToken(['access_token' => 'user-facebook-access-token']);
$userProfile = $adapter->getUserProfile();
// print_r($userProfile);
$adapter->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}
+31
View File
@@ -0,0 +1,31 @@
<?php
/*!
* A simple example that shows how to connect users to providers using OpenID.
*/
include 'vendor/autoload.php';
$config = [
'callback' => Hybridauth\HttpClient\Util::getCurrentUrl(),
'openid_identifier' => 'https://open.login.yahooapis.com/openid20/www.yahoo.com/xrds',
// 'openid_identifier' => 'https://openid.stackexchange.com/',
// 'openid_identifier' => 'http://steamcommunity.com/openid',
// etc.
];
try {
$adapter = new Hybridauth\Provider\OpenID($config);
$adapter->authenticate();
$tokens = $adapter->getAccessToken();
$userProfile = $adapter->getUserProfile();
// print_r($tokens);
// print_r($userProfile);
$adapter->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}
+32
View File
@@ -0,0 +1,32 @@
<?php
/*!
* A simple example that shows how to use Guzzle as a Http Client for Hybridauth instead of PHP Curl extention.
*/
include 'vendor/autoload.php';
$config = [
'callback' => Hybridauth\HttpClient\Util::getCurrentUrl(),
'keys' => ['id' => '', 'secret' => ''],
];
$guzzle = new Hybridauth\HttpClient\Guzzle(null, [
// 'verify' => true, # Set to false to disable SSL certificate verification
]);
try {
$adapter = new Hybridauth\Provider\Github($config, $guzzle);
$adapter->authenticate();
$tokens = $adapter->getAccessToken();
$userProfile = $adapter->getUserProfile();
// print_r($tokens);
// print_r($userProfile);
$adapter->disconnect();
} catch (Exception $e) {
echo $e->getMessage();
}
@@ -0,0 +1,59 @@
<?php
/**
* A simple example that shows how to use multiple providers.
*/
include 'vendor/autoload.php';
include 'config.php';
use Hybridauth\Exception\Exception;
use Hybridauth\Hybridauth;
use Hybridauth\HttpClient;
use Hybridauth\Storage\Session;
try {
/**
* Feed configuration array to Hybridauth.
*/
$hybridauth = new Hybridauth($config);
/**
* Initialize session storage.
*/
$storage = new Session();
/**
* Hold information about provider when user clicks on Sign In.
*/
if (isset($_GET['provider'])) {
$storage->set('provider', $_GET['provider']);
}
/**
* When provider exists in the storage, try to authenticate user and clear storage.
*
* When invoked, `authenticate()` will redirect users to provider login page where they
* will be asked to grant access to your application. If they do, provider will redirect
* the users back to Authorization callback URL (i.e., this script).
*/
if ($provider = $storage->get('provider')) {
$hybridauth->authenticate($provider);
$storage->set('provider', null);
}
/**
* This will erase the current user authentication data from session, and any further
* attempt to communicate with provider.
*/
if (isset($_GET['logout'])) {
$adapter = $hybridauth->getAdapter($_GET['logout']);
$adapter->disconnect();
}
/**
* Redirects user to home page (i.e., index.php in our case)
*/
HttpClient\Util::redirect('https://path/to/hybridauth/examples/example_06');
} catch (Exception $e) {
echo $e->getMessage();
}
@@ -0,0 +1,35 @@
<?php
/**
* Build a configuration array to pass to `Hybridauth\Hybridauth`
*/
$config = [
/**
* Set the Authorization callback URL to https://path/to/hybridauth/examples/example_06/callback.php.
* Understandably, you need to replace 'path/to/hybridauth' with the real path to this script.
*/
'callback' => 'https://path/to/hybridauth/examples/example_06/callback.php',
'providers' => [
'Twitter' => [
'enabled' => true,
'keys' => [
'key' => '...',
'secret' => '...',
],
],
'LinkedIn' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...',
],
],
'Facebook' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...',
],
],
],
];
@@ -0,0 +1,49 @@
<?php
/**
* Build a simple HTML page with multiple providers.
*/
include 'vendor/autoload.php';
include 'config.php';
use Hybridauth\Hybridauth;
$hybridauth = new Hybridauth($config);
$adapters = $hybridauth->getConnectedAdapters();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example 06</title>
</head>
<body>
<h1>Sign in</h1>
<ul>
<?php foreach ($hybridauth->getProviders() as $name) : ?>
<?php if (!isset($adapters[$name])) : ?>
<li>
<a href="<?php print $config['callback'] . "?provider={$name}"; ?>">
Sign in with <strong><?php print $name; ?></strong>
</a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php if ($adapters) : ?>
<h1>You are logged in:</h1>
<ul>
<?php foreach ($adapters as $name => $adapter) : ?>
<li>
<strong><?php print $adapter->getUserProfile()->displayName; ?></strong> from
<i><?php print $name; ?></i>
<span>(<a href="<?php print $config['callback'] . "?logout={$name}"; ?>">Log Out</a>)</span>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</body>
</html>
@@ -0,0 +1,99 @@
<?php
/**
* A simple example that shows how to use multiple providers, opening provider authentication in a pop-up.
*/
require 'path/to/vendor/autoload.php';
require 'config.php';
use Hybridauth\Exception\Exception;
use Hybridauth\Hybridauth;
use Hybridauth\HttpClient;
use Hybridauth\Storage\Session;
try {
$hybridauth = new Hybridauth($config);
$storage = new Session();
$error = false;
//
// Event 1: User clicked SIGN-IN link
//
if (isset($_GET['provider'])) {
// Validate provider exists in the $config
if (in_array($_GET['provider'], $hybridauth->getProviders())) {
// Store the provider for the callback event
$storage->set('provider', $_GET['provider']);
} else {
$error = $_GET['provider'];
}
}
//
// Event 2: User clicked LOGOUT link
//
if (isset($_GET['logout'])) {
if (in_array($_GET['logout'], $hybridauth->getProviders())) {
// Disconnect the adapter
$adapter = $hybridauth->getAdapter($_GET['logout']);
$adapter->disconnect();
} else {
$error = $_GET['logout'];
}
}
//
// Handle invalid provider errors
//
if ($error) {
error_log('Hybridauth Error: Provider ' . json_encode($error) . ' not found or not enabled in $config');
// Close the pop-up window
echo "
<script>
if (window.opener.closeAuthWindow) {
window.opener.closeAuthWindow();
}
</script>";
exit;
}
//
// Event 3: Provider returns via CALLBACK
//
if ($provider = $storage->get('provider')) {
$hybridauth->authenticate($provider);
$storage->set('provider', null);
// Retrieve the provider record
$adapter = $hybridauth->getAdapter($provider);
$userProfile = $adapter->getUserProfile();
$accessToken = $adapter->getAccessToken();
// add your custom AUTH functions (if any) here
// ...
$data = [
'token' => $accessToken,
'identifier' => $userProfile->identifier,
'email' => $userProfile->email,
'first_name' => $userProfile->firstName,
'last_name' => $userProfile->lastName,
'photoURL' => strtok($userProfile->photoURL, '?'),
];
// ...
// Close pop-up window
echo "
<script>
if (window.opener.closeAuthWindow) {
window.opener.closeAuthWindow();
}
</script>";
}
} catch (Exception $e) {
error_log($e->getMessage());
echo $e->getMessage();
}
@@ -0,0 +1,27 @@
<?php
/**
* Build a configuration array to pass to `Hybridauth\Hybridauth`
*
* Set the Authorization callback URL to https://path/to/hybridauth/examples/example_07/callback.php
* Understandably, you need to replace 'path/to/hybridauth' with the real path to this script.
*/
$config = [
'callback' => 'https://path/to/hybridauth/examples/example_07/callback.php',
'providers' => [
'Google' => [
'enabled' => true,
'keys' => [
'id' => '...',
'secret' => '...',
],
'scope' => 'email',
],
// 'Yahoo' => ['enabled' => true, 'keys' => ['key' => '...', 'secret' => '...']],
// 'Facebook' => ['enabled' => true, 'keys' => ['id' => '...', 'secret' => '...']],
// 'Twitter' => ['enabled' => true, 'keys' => ['key' => '...', 'secret' => '...']],
// 'Instagram' => ['enabled' => true, 'keys' => ['id' => '...', 'secret' => '...']],
],
];
@@ -0,0 +1,65 @@
<?php
/**
* Build a simple HTML page with multiple providers, opening provider authentication in a pop-up.
*/
require 'path/to/vendor/autoload.php';
require 'config.php';
use Hybridauth\Hybridauth;
$hybridauth = new Hybridauth($config);
$adapters = $hybridauth->getConnectedAdapters();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example 07</title>
<script>
function auth_popup(provider) {
// replace 'path/to/hybridauth' with the real path to this script
var authWindow = window.open('https://path/to/hybridauth/examples/example_07/callback.php?provider=' + provider, 'authWindow', 'width=600,height=400,scrollbars=yes');
window.closeAuthWindow = function () {
authWindow.close();
}
return false;
}
</script>
</head>
<body>
<h1>Sign in</h1>
<ul>
<?php foreach ($hybridauth->getProviders() as $name) : ?>
<?php if (!isset($adapters[$name])) : ?>
<li>
<a href="#" onclick="javascript:auth_popup('<?php print $name ?>');">
Sign in with <?php print $name ?>
</a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php if ($adapters) : ?>
<h1>You are logged in:</h1>
<ul>
<?php foreach ($adapters as $name => $adapter) : ?>
<li>
<strong><?php print $adapter->getUserProfile()->displayName; ?></strong> from
<i><?php print $name; ?></i>
<span>(<a href="<?php print $config['callback'] . "?logout={$name}"; ?>">Log Out</a>)</span>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
403.