/** * @param array $params * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider]; $client = new \OAuth2\Client($oAuthConf['clientId'], $oAuthConf['clientSecret'], \OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_BEARER); $response = $client->getAccessToken('https://ssl.reddit.com/api/v1/access_token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); // Reddit requires a User-Agent $info = $client->fetch("https://oauth.reddit.com/api/v1/me.json", array(), 'GET', array('User-Agent' => 'destiny.gg/' . Config::version())); if (empty($info['result']) || !is_array($info['result']) || isset($info['error'])) { throw new Exception('Invalid user details response'); } $authCreds = $this->getAuthCredentials($params['code'], $info['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * @param array $params * @throws Exception */ public function authenticate(array $params, ViewModel $model) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $oAuthConf = Config::$a['oauth']['providers'][$this->authProvider]; $client = new \OAuth2\Client($oAuthConf['clientId'], $oAuthConf['clientSecret']); $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_OAUTH); $response = $client->getAccessToken('https://api.twitch.tv/kraken/oauth2/token', 'authorization_code', array('redirect_uri' => sprintf(Config::$a['oauth']['callback'], $this->authProvider), 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); $response = $client->fetch('https://api.twitch.tv/kraken/user'); if (empty($response['result']) || isset($response['error'])) { throw new Exception('Invalid user details response'); } if (is_string($response['result'])) { throw new Exception(sprintf('Invalid auth result %s', $response['result'])); } $authCreds = $this->getAuthCredentials($params['code'], $response['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
/** * Registers services on the given app. * * This method should only be used to configure services and parameters. * It should not get services. */ public function register(Application $app) { $app['oauth_client_id'] = ''; $app['oauth_client_secret'] = ''; $app['oauth_client'] = $app->share(function (Application $app) { $client = new \OAuth2\Client($app['oauth_client_id'], $app['oauth_client_secret']); $session = $app['request']->getSession(); if ($session->has('oauth_access_token')) { $client->setAccessToken($session->get('oauth_access_token')); $client->setAccessTokenType(\OAuth2\Client::ACCESS_TOKEN_BEARER); } return $client; }); $app['oauth_base_url'] = function (Application $app) { if ($app['session']->has('slug')) { return sprintf('https://%s.nationbuilder.com/', $app['session']->get('slug')); } return false; }; $app['oauth_url'] = function (Application $app) { if ($app['session']->has('slug')) { return sprintf('https://%s.nationbuilder.com/api/v1/', $app['session']->get('slug')); } return false; }; $app['oauth_auth_url'] = function (Application $app) { if ($app['session']->has('slug')) { return sprintf('https://%s.nationbuilder.com/oauth/', $app['session']->get('slug')); } return false; }; }
/** * approve method * * @return void */ public function approve() { $client = new OAuth2\Client(Configure::read('LilCrm.googleApiClientId'), Configure::read('LilCrm.googleApiClientSecret')); $redirect_url = Router::url(array('prefix' => false, 'plugin' => 'lil_crm', 'controller' => 'oauth', 'action' => 'index'), true); $auth_url = $client->getAuthenticationUrl('https://accounts.google.com/o/oauth2/auth', $redirect_url, array('scope' => 'http://www.google.com/m8/feeds/', 'access_type' => 'offline')); header('Location: ' . $auth_url); die('Redirect'); }
/** * New OAuth2 Client */ function NewClient() { global $QBOX_ACCESS_KEY, $QBOX_SECRET_KEY; $client = new \OAuth2\Client('a75604760c4da4caaa456c0c5895c061c3065c5a', '75df554a39f58accb7eb293b550fa59618674b7d'); $client->setAccessTokenType($client::ACCESS_TOKEN_QBOX, $QBOX_SECRET_KEY, null); $client->setAccessToken($QBOX_ACCESS_KEY); return $client; }
public function callbackAction() { $callback_url = Mage::getUrl('gomage_social/reddit/callback', array('_secure' => true)); $client = new OAuth2\Client(Mage::getStoreConfig('gomage_social/reddit/id'), Mage::getStoreConfig('gomage_social/reddit/secret'), OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $params = array("code" => $this->getRequest()->getParam('code'), "redirect_uri" => $callback_url); if ($params['code']) { $response = $client->getAccessToken($this->accessTokenUrl, "authorization_code", $params); $accessTokenResult = $response["result"]; $client->setAccessToken($accessTokenResult["access_token"]); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); $response = (object) $client->fetch("https://oauth.reddit.com/api/v1/me.json"); $profile = null; switch ($response->code) { case 200: $profile = (object) $response->result; break; default: $this->getSession()->addError($this->__('Could not connect to Reddit. Refresh the page or try again later.')); return $this->_redirectUrl(); } if ($profile) { if ($profile->id) { $social_collection = Mage::getModel('gomage_social/entity')->getCollection()->addFieldToFilter('social_id', $profile->id)->addFieldToFilter('type_id', GoMage_Social_Model_Type::REDDIT); if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) { $social_collection->addFieldToFilter('website_id', Mage::app()->getWebsite()->getId()); } $social = $social_collection->getFirstItem(); if ($social && $social->getId()) { if ($social->social_id == $profile->id) { $customer = Mage::getModel('customer/customer'); if (Mage::getSingleton('customer/config_share')->isWebsiteScope()) { $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); } $customer->load($social->getData('customer_id')); if ($customer && $customer->getId()) { if (!$customer->getConfirmation()) { $this->getSession()->loginById($customer->getId()); } else { $this->getSession()->addError($this->__('This account is not confirmed.')); } } } } else { $profile->url = Mage::getUrl('gomage_social/reddit/checkEmail', array('_secure' => true)); $profile->urlEmailClose = Mage::getUrl('gomage_social/twitter/emailClose', array('_secure' => true)); $profile->type_id = GoMage_Social_Model_Type::REDDIT; Mage::getSingleton('core/session')->setGsProfile($profile); } } } } return $this->_redirectUrl(); }
/** * Attempts to get an access token. * * @return * TRUE if an access token was retrieved; FALSE otherwise. */ public function getAccessToken() { // Configure the OAuth2 client. $oauth2_config = array('auth_flow' => 'user-password', 'token_endpoint' => variable_get('oauth2_authentication_token_endpoint', ''), 'client_id' => variable_get('oauth2_authentication_client_id', ''), 'client_secret' => variable_get('oauth2_authentication_client_secret', ''), 'scope' => variable_get('oauth2_authentication_scope', ''), 'username' => $this->username, 'password' => $this->password); try { // Create an OAuth2 client and attempt to get an access token. If we // aren't able to, we'll end up in the catch stanza as an exception will // be thrown. $oauth2_client = new OAuth2\Client($oauth2_config); $token = $oauth2_client->getAccessToken(); $token_retrieved = isset($token); } catch (Exception $e) { // We couildn't get an access token for this user so it must not be valid. $token_retrieved = FALSE; } // Report status in the log. watchdog('oauth2_authentication', 'Access token requested for user %name: !result', array('%name' => $this->username, '!result' => $token_retrieved ? 'SUCCESS' : 'FAILURE')); // Return the result. return $token_retrieved; }
/** * Intercept all OAuth2\Client::getResponse() calls and mock their responses */ public function mockGetResponse() { // retrieve arguments $args = func_get_args(); // map routes $map = array(); $map['GET']['/success'] = array('status' => 200, 'headers' => array('Content-Type' => 'text/awesome'), 'body' => 'yay'); $map['GET']['/reflect'] = array('status' => 200, 'headers' => array(), 'body' => $args[0]->getBody()); $map['POST']['/reflect'] = array('status' => 200, 'headers' => array(), 'body' => $args[0]->getBody()); $map['GET']['/unauthorized'] = array('status' => 401, 'headers' => array('Content-Type' => 'application/json'), 'body' => json_encode(array('error' => $this->errorValue, 'error_description' => $this->errorDescriptionValue))); $map['GET']['/conflict'] = array('status' => 409, 'headers' => array('Content-Type' => 'text/plain'), 'body' => 'not authorized'); $map['GET']['/redirect'] = array('status' => 302, 'headers' => array('Content-Type' => 'text/plain', 'location' => '/success'), 'body' => ''); $map['POST']['/redirect'] = array('status' => 303, 'headers' => array('Content-Type' => 'text/plain', 'location' => '/reflect'), 'body' => ''); $map['GET']['/error'] = array('status' => 500, 'headers' => array(), 'body' => ''); $map['GET']['/empty_get'] = array('status' => 200, 'headers' => array(), 'body' => ''); // match response $response = $map[$args[0]->getMethod()][$args[0]->getPath()]; // wrap response in an OAuth2\Response object $response = new \OAuth2\Response(new \GuzzleHttp\Message\Response($response['status'], $response['headers'], \GuzzleHttp\Stream\Stream::factory($response['body'])), $args[1]); // handle response if (in_array($response->status(), range(200, 299))) { return $response; } else { if (in_array($response->status(), range(300, 399))) { // Increment redirect count $this->client->options['redirect_count'] = isset($this->client->options['redirect_count']) ? $this->client->options['redirect_count'] : 0; $this->client->options['redirect_count'] += 1; if ($this->client->options['redirect_count'] > $args[0]->getConfig()['redirect']['max']) { return $response; } // Retrieve data $method = $response->status() === 303 ? 'GET' : $args[0]->getMethod(); $headers = $response->headers(); $location = $headers['location']; // Redirect request $request = $this->client->createRequest($method, $location[0], ['body' => $response->body()]); return $this->client->getResponse($request); } else { if (in_array($response->status(), range(400, 599))) { $e = new \OAuth2\Error($response); if ($args[0]->getConfig()['exceptions'] || $this->client->options['request_opts']['exceptions']) { throw $e; } $response->error = $e; return $response; } else { throw new \OAuth2\Error($response); } } } }
/** * @param array $params * @throws Exception */ public function authenticate(array $params) { if (!isset($params['code']) || empty($params['code'])) { throw new Exception('Authentication failed, invalid or empty code.'); } $authConf = Config::$a['oauth']['providers'][$this->authProvider]; $callback = sprintf(Config::$a['oauth']['callback'], $this->authProvider); $client = new \OAuth2\Client($authConf['clientId'], $authConf['clientSecret']); $response = $client->getAccessToken('https://accounts.google.com/o/oauth2/token', 'authorization_code', array('redirect_uri' => $callback, 'code' => $params['code'])); if (empty($response) || isset($response['error'])) { throw new Exception('Invalid access_token response'); } if (!isset($response['result']) || empty($response['result']) || !isset($response['result']['access_token'])) { throw new Exception('Failed request for access token'); } $client->setAccessToken($response['result']['access_token']); $response = $client->fetch('https://www.googleapis.com/oauth2/v2/userinfo'); if (empty($response['result']) || isset($response['error'])) { throw new Exception('Invalid user details response'); } $authCreds = $this->getAuthCredentials($params['code'], $response['result']); $authCredHandler = new AuthenticationRedirectionFilter(); return $authCredHandler->execute($authCreds); }
<?php require_once '../vendor/PHP-OAuth2/Client.php'; require_once '../vendor/PHP-OAuth2/GrantType/IGrantType.php'; require_once '../vendor/PHP-OAuth2/GrantType/AuthorizationCode.php'; require_once '../vendor/icalforce/oauth.inc.php'; $client = new OAuth2\Client($CLIENT_ID, $CLIENT_SECRET); $keyInfo = ICalForce\cookieMakeCryptKey(); if (isset($_GET['code'])) { $params = array('code' => $_GET['code'], 'redirect_uri' => $REDIRECT_URI); $response = $client->getAccessToken(ICalForce\TOKEN_ENDPOINT, 'authorization_code', $params); $cookieEnc = ICalForce\cookieEncrypt($keyInfo, json_encode($response)); setcookie('V_04660A06A99FEC845360DA2C6D2557A3', $cookieEnc, 0, '/', $_SERVER['HTTP_HOST'], true); header('Location: ' . $HOME_URI); die('Redirect'); } elseif (isset($_GET['error'])) { echo 'Error. Could not get Auth-Token. Please contact your system administrator.'; } else { $auth_url = $client->getAuthenticationUrl(ICalForce\AUTHORIZATION_ENDPOINT, $REDIRECT_URI); header('Location: ' . $auth_url); die('Redirect'); }
const AUTHORIZATION_ENDPOINT = 'https://www.deviantart.com/oauth2/authorize'; const TOKEN_ENDPOINT = 'https://www.deviantart.com/oauth2/token'; const SUBMIT_API = "https://www.deviantart.com/api/oauth2/stash/submit"; const FOLDER_API = "https://www.deviantart.com/api/oauth2/stash/folder"; const APPNAME = 'App.Name'; echo '<a href="' . REDIRECT_URI . '">Reload</a><br>'; /** * Oauth2 Process * * 1. Ask user to authorize by redirecting them to the authorization endpoint on DA * 2. Once user authorizes DA will send back an authoirzation code ($_GET['code']) * 3. We then use the code to get an access_token * 4. We use the access_token to access an API endpoint */ try { $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); if (!isset($_REQUEST['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirecting ...'); } else { $params = array('code' => $_REQUEST['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, OAuth2\Client::GRANT_TYPE_AUTH_CODE, $params); $val = (object) $response['result']; if (!$val->access_token) { throw new Exception("No access token returned: " . $val->error_description); } $client->setAccessToken($val->access_token); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_OAUTH); // Submit a file first $response = $client->fetch(SUBMIT_API, array('title' => 'Fella Sample Image', 'artist_comments' => 'Fella Sample Image', 'keywords' => 'fella sample image', 'folder' => APPNAME, 'file' => "@fella.png"), OAuth2\Client::HTTP_METHOD_POST);
<?php session_start(); require_once 'inc.config.php'; require 'Client.php'; require 'IGrantType.php'; require 'AuthorizationCode.php'; /******************************************************************************* * IDENTIFICATION ******************************************************************************/ $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://"; $url = $protocol . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI']; //DECONNEXION if (isset($_GET['reset'])) { unset($_SESSION['access_token']); header('Content-type: application/json'); echo json_encode(array(DISCONNECT_PAGE)); } elseif (!empty($_SESSION['access_token'])) { $client->setAccessToken($_SESSION['access_token']); $profile = $client->fetch(PROFILE_PAGE); } elseif (empty($_GET['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, $url); header('Location: ' . $auth_url); die('Redirect'); } else { $params = array('code' => $_GET['code'], 'redirect_uri' => $url); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); if (isset($response['result']) && isset($response['result']['access_token'])) { $client->setAccessToken($response['result']['access_token']); $_SESSION['access_token'] = $response['result']['access_token'];
/** * @return \OAuth2\Client|null */ public function GoogleConnector() { $oGoogle = false; $oConfig = $this->oActions->Config(); if ($oConfig->Get('social', 'google_enable', false) && '' !== \trim($oConfig->Get('social', 'google_client_id', '')) && '' !== \trim($oConfig->Get('social', 'google_client_secret', ''))) { include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHP-OAuth2/Client.php'; include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHP-OAuth2/GrantType/IGrantType.php'; include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHP-OAuth2/GrantType/AuthorizationCode.php'; include_once APP_VERSION_ROOT_PATH . 'app/libraries/PHP-OAuth2/GrantType/RefreshToken.php'; try { $oGoogle = new \OAuth2\Client(\trim($oConfig->Get('social', 'google_client_id', '')), \trim($oConfig->Get('social', 'google_client_secret', ''))); $sProxy = $this->oActions->Config()->Get('labs', 'curl_proxy', ''); if (0 < \strlen($sProxy)) { $oGoogle->setCurlOption(CURLOPT_PROXY, $sProxy); $sProxyAuth = $this->oActions->Config()->Get('labs', 'curl_proxy_auth', ''); if (0 < \strlen($sProxyAuth)) { $oGoogle->setCurlOption(CURLOPT_PROXYUSERPWD, $sProxyAuth); } } } catch (\Exception $oException) { $this->oActions->Logger()->WriteException($oException, \MailSo\Log\Enumerations\Type::ERROR); } } return false === $oGoogle ? null : $oGoogle; }
session_start(); if (isset($_GET["error"])) { echo "<pre>OAuth Error: " . $_GET["error"] . "\n"; echo '<a href="index.php">Retry</a></pre>'; die; } $authorizeUrl = 'https://github.com/login/oauth/authorize'; $accessTokenUrl = 'https://github.com/login/oauth/access_token'; $clientId = $_SERVER['OAUTH2_CLIENT_ID']; $clientSecret = $_SERVER['OAUTH2_CLIENT_SECRET']; $userAgent = 'cwalk'; $redirectUrl = "http://www.cwalk.guru/login.php"; require "OAuth2/Client.php"; require "OAuth2/GrantType/IGrantType.php"; require "OAuth2/GrantType/AuthorizationCode.php"; $client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setCurlOption(CURLOPT_USERAGENT, $userAgent); if (!isset($_GET["code"])) { $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array("scope" => "user,user:email", "state" => "SomeUnguessableValue")); header("Location: " . $authUrl); die("Redirect"); } else { $params = array("code" => $_GET["code"], "redirect_uri" => $redirectUrl); $response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params); $accessTokenResult = $response["result"]; parse_str($accessTokenResult, $accessTokenResultArray); $accessTokenFirst = $accessTokenResultArray["access_token"]; $accessToken = $accessTokenResultArray["access_token"]; $client->setAccessToken($accessToken); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); $response = $client->fetch("https://api.github.com/user");
/** * Add the necessary webhooks for the Sausage Machine to function * @param String $github_access_token see route_get_github_auth & route_get_github_auth_callback * @param String $github_repo GitHub username, followed by a slash, followed by the name of the respository * @return true if sucessful, false if not */ function github_add_webhook($github_access_token, $github_repo) { $client = new OAuth2\Client(config('github_client_id'), config('github_client_secret')); $client->setAccessToken($github_access_token); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_TOKEN); $client->setCurlOption(CURLOPT_USERAGENT, config('github_useragent')); $param = array('name' => 'web', 'active' => true, 'events' => array('push'), 'config' => array('url' => base_url() . 'github.php?push', 'content_type' => 'form')); $response = $client->fetch('https://api.github.com/repos/' . $github_repo . '/hooks', json_encode($param), 'POST'); if (!isset($response['code']) || $response['code'] !== 201) { return false; } else { return true; } }
<?php include 'config.php'; $client = new OAuth2\Client($clientId, $clientSecret); if (!isset($_GET['code'])) { $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl); header('Location: ' . $authUrl); die('Redirect'); } else { $params = array('code' => $_GET['code'], 'redirect_uri' => $redirectUrl); $response = $client->getAccessToken($accessTokenUrl, 'authorization_code', $params); $token = $response['result']['access_token']; $client->setAccessTokenType(1); $client->setAccessToken($token); $_SESSION['client'] = $client; $_SESSION['token'] = $token; header('Location: index.php'); }
<?php spl_autoload_register(function ($class) { require str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php'; }); // configuration of client credentials $client = new OAuth2\Client('CLIENT_ID', 'CLIENT_SECRET', 'CALLBACK_URL'); // or use without callback_url, use in desktop application $client = new OAuth2\Client('CLIENT_ID', 'CLIENT_SECRET'); // configuration of service $configuration = new OAuth2\Service\Configuration('AUTHORIZE_ENDPOINT', 'ACCESS_TOKEN_ENDPOINT', 'REVOKE_ENDPOINT'); // storage class for access token, just implement OAuth2\DataStore interface for // your own implementation $dataStore = new OAuth2\DataStore\Session(); $scope = null; $service = new OAuth2\Service($client, $configuration, $dataStore, $scope); if (isset($_GET['action'])) { switch ($_GET['action']) { case 'authorize': // redirects to authorize endpoint $service->authorize(); break; case 'requestApi': // calls api endpoint with access token echo $service->callApiEndpoint('API_ENDPOINT'); break; case 'revoke': // calls revoke access token echo $service->revokeAccessToken(); break; }
<?php require_once __DIR__ . '/../vendor/autoload.php'; use PositionlyApi\PositionlyApi; require '_credentials.php'; $client = new OAuth2\Client($clientId, $clientSecret); $authorizationParams = array('username' => $username, 'password' => $password); $result = $client->getAccessToken(PositionlyApi::getTokenEndpoint(), 'password', $authorizationParams); $accessToken = json_decode($result['result'], true); $client->setAccessToken($accessToken['access_token']); $api = new PositionlyApi($client); // get accounts $response = $api->call('/accounts'); // get first account id $accountId = $response->getResult()[0]['id']; // get first website id $response = $api->call(sprintf('/accounts/%s/websites', $accountId)); $websiteId = $response->getResult()[0]['id']; // get first keyword id $response = $api->call(sprintf('/accounts/%s/websites/%s/keywords', $accountId, $websiteId)); $keywordId = $response->getResult()[0]['id']; $engineId = 43; // google polska $response = $api->call(sprintf('/accounts/%s/websites/%s/engines/%s/keywords/%s/positions', $accountId, $websiteId, $engineId, $keywordId)); if ($response->isSuccess()) { echo 'Success!'; } else { echo 'Failure'; } print_r($response); exit;
/** * User-Login for Facebook * * @param $strUsername * @param $strPassword * @param $boolUseHash Use Hash for comparing * @return bool/array */ public function login($strUsername, $strPassword, $boolUseHash = false) { $blnLoginResult = false; $this->init_oauth(); if ($this->in->get('norelay', 0)) { $code = $_GET['code']; } else { $encrypt = register('encrypt', array($this->eqdkp_appsecret)); $code = $encrypt->decrypt(rawurldecode($_GET['code'])); } if ($code) { $client = new OAuth2\Client($this->appid, $this->appsecret); if ($this->relay) { $time = $this->in->get('t'); $hmac = $this->in->get('h'); $s = $this->in->get('_s') ? '&_s=' . $this->in->get('_s') : ''; $redir_url = $this->RELAY_URL . '?_t=' . $time . '&_id=' . $this->eqdkp_appid . '&_hmac=' . $hmac . $s; } else { $redir_url = $this->env->buildLink() . 'index.php/Login/?login&lmethod=battlenet&norelay=1'; } $params = array('code' => $code, 'redirect_uri' => $redir_url, 'scope' => 'wow.profile'); $response = $client->getAccessToken($this->TOKEN_ENDPOINT, 'authorization_code', $params); if ($response && $response['result']) { if (isset($response['result']['accountId'])) { $userid = $this->pdh->get('user', 'userid_for_authaccount', array($response['result']['accountId'], 'battlenet')); if ($userid) { $userdata = $this->pdh->get('user', 'data', array($userid)); if ($userdata) { list($strPwdHash, $strSalt) = explode(':', $userdata['user_password']); return array('status' => 1, 'user_id' => $userdata['user_id'], 'password_hash' => $strPwdHash, 'autologin' => true, 'user_login_key' => $userdata['user_login_key']); } } } } } return false; }
<?php require_once 'vendor/autoload.php'; const CLIENT_ID = 'testclient'; const CLIENT_SECRET = 'testpass'; const REDIRECT_URI = 'http://localhost/oauth2/php_oauth_client/www/index.php'; const AUTHORIZATION_ENDPOINT = 'http://localhost:81/oauth/authorize'; const TOKEN_ENDPOINT = 'http://localhost:81/oauth/token'; $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); $get = (object) filter_input_array(INPUT_GET, ['code' => FILTER_SANITIZE_STRING, 'error' => FILTER_SANITIZE_STRING, 'error_description' => FILTER_SANITIZE_STRING, 'get_access' => FILTER_VALIDATE_BOOLEAN]); if (@$get->error) { echo "<a href='{$_SERVER['PHP_SELF']}'>retry</a><br>"; die("<b>{$get->error}</b><br>{$get->error_description}"); } if (!@$get->code && @$get->get_access) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI, ['state' => uniqid()]); header('Location: ' . $auth_url); die('Redirect'); } if (@$get->code) { $params = array('code' => $get->code, 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); echo "<b>Access token:</b> " . $response['result']['access_token'] . '<br>'; echo "<a href='{$_SERVER['PHP_SELF']}'>back</a><br>"; } else { } echo "<a href='{$_SERVER['PHP_SELF']}?get_access=true'>get access</a><br>";
<?php require 'oauth2/Client.php'; require "oauth2/GrantType/IGrantType.php"; require "oauth2/GrantType/AuthorizationCode.php"; require "oauth2/GrantType/RefreshToken.php"; const CLIENT_ID = 'CLIENT_ID'; const CLIENT_SECRET = 'CLIENT_SECRET'; const REDIRECT_URI = 'REDIRECT_URI'; const AUTHORIZATION_ENDPOINT = 'https://api.parasut.com/oauth/authorize'; const TOKEN_ENDPOINT = 'https://api.parasut.com/oauth/token'; $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); if (!isset($_GET['code'])) { // authentication call $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI); header('Location: ' . $auth_url); die('Redirect'); } else { // access token request $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); // CAUTION! instead of parse_str, assign response directly to $info or find an alternative way. // parse_str($response['result'], $info); $info = $response['result']; $accessToken = $info['access_token']; $refreshToken = $info['refresh_token']; print_r($info); echo "<br /><br /><br />"; // set access token for further api calls $client->setAccessToken($accessToken); // example api call
if (isset($_GET["error"])) { echo "<pre>OAuth Error: " . $_GET["error"] . "\n"; echo '<a href="index.php">Retry</a></pre>'; die; //?state=SomeUnguessableValue&code=ki4tr-_EAXNXVrhWMcQ5a5pLm0o } $authorizeUrl = 'https://ssl.reddit.com/api/v1/authorize'; $accessTokenUrl = 'https://ssl.reddit.com/api/v1/access_token'; $clientId = 'jJgLD5ebMOT9sw'; $clientSecret = 'muldwiysWI2ok2KWNmoiDK6FMKw'; $userAgent = 'ChangeMeClient/0.1 by YourUsername'; $redirectUrl = "http://brittanyannkos.com/reddit"; require "OAuth2/Client.php"; require "OAuth2/GrantType/IGrantType.php"; require "OAuth2/GrantType/AuthorizationCode.php"; $client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC); $client->setCurlOption(CURLOPT_USERAGENT, $userAgent); $_GET["code"] = "ki4tr-_EAXNXVrhWMcQ5a5pLm0o"; if (!isset($_GET["code"])) { $authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array("scope" => "identity", "state" => "SomeUnguessableValue", "duration" => "permanent")); header("Location: " . $authUrl); die("Redirect"); } else { $params = array("code" => $_GET["code"], "redirect_uri" => $redirectUrl); $response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params); $accessTokenResult = $response["result"]; print_r($accessTokenResult); $client->setAccessToken($accessTokenResult["access_token"]); $client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER); $response = $client->fetch("https://oauth.reddit.com/api/v1/me.json"); echo '<strong>Response for fetch me.json:</strong><pre>';
<?php require 'client.php'; require 'GrantType/IGrantType.php'; require 'GrantType/AuthorizationCode.php'; const CLIENT_ID = '379875764619-57lesbrrec02g9tf3r2d2gup6nvdl3p4.apps.googleusercontent.com'; const CLIENT_SECRET = 'KeHot5Ds76apeUcrE27xXYJH'; const REDIRECT_URI = 'http://localhost/oauth/test.php'; const AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/auth'; const TOKEN_ENDPOINT = 'https://accounts.google.com/o/oauth2/token'; //localhost/oauth/test.php session_start(); $client = new OAuth2\Client(CLIENT_ID, CLIENT_SECRET); if (!isset($_GET['code'])) { $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI, array('scope' => 'http://www.google.com/m8/feeds/', 'access_type' => 'offline')); header('Location: ' . $auth_url); die('Redirect'); } else { if (empty($_SESSION['token'])) { $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI); $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); if ($response['code'] == 200) { $_SESSION['token'] = $response['result']['access_token']; } } if (!empty($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); $response = $client->fetch('https://www.google.com/m8/feeds/contacts/default/full'); if ($response['code'] == 200) { $response = json_encode(simplexml_load_string($response['result'])); print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";