In oder to acquire access token perform following sequence:
php
use yii\authclient\OAuth2;
assuming class MyAuthClient extends OAuth2
$oauthClient = new MyAuthClient();
$url = $oauthClient->buildAuthUrl(); // Build authorization URL
Yii::$app->getResponse()->redirect($url); // Redirect to authorization URL.
After user returns at our site:
$code = $_GET['code'];
$accessToken = $oauthClient->fetchAccessToken($code); // Get access token
public function testBuildAuthUrl() { $oauthClient = new OAuth2(); $authUrl = 'http://test.auth.url'; $oauthClient->authUrl = $authUrl; $clientId = 'test_client_id'; $oauthClient->clientId = $clientId; $returnUrl = 'http://test.return.url'; $oauthClient->setReturnUrl($returnUrl); $builtAuthUrl = $oauthClient->buildAuthUrl(); $this->assertContains($authUrl, $builtAuthUrl, 'No auth URL present!'); $this->assertContains($clientId, $builtAuthUrl, 'No client id present!'); $this->assertContains(rawurlencode($returnUrl), $builtAuthUrl, 'No return URL present!'); }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->scope === null) { $this->scope = implode(' ', ['profile', 'email']); } }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->scope === null) { $this->scope = implode(' ', ['r_basicprofile', 'r_emailaddress']); } }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->scope === null) { $this->scope = 'user'; } }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->scope === null) { $this->scope = implode(' ', ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email']); } }
/** * @inheritdoc */ public function applyAccessTokenToRequest($request, $accessToken) { parent::applyAccessTokenToRequest($request, $accessToken); $data = $request->getData(); $data['appsecret_proof'] = hash_hmac('sha256', $accessToken->getToken(), $this->clientSecret); $request->setData($data); }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->scope === null) { $this->scope = implode(' ', ['user', 'user:email']); } }
/** * @inheritdoc */ public function init() { parent::init(); if ($this->scope === null) { $this->scope = implode(',', ['wl.basic', 'wl.emails']); } }
public function init() { parent::init(); if ($this->scope === null) { $this->scope = implode(',', ['get_user_info']); } }
public function actionSuccess() { $session = \Yii::$app->session; $request = \Yii::$app->request; $authHeader = 'Authorization: Basic ' . base64_encode("{$this->clientId}:{$this->secret}"); $contentHeader = 'Content-Type: application/x-www-form-urlencoded'; $httpHeaders = array($authHeader, $contentHeader); $oauth = new OAuth2(); $oauth->clientId = $this->clientId; $oauth->clientSecret = $this->secret; $oauth->returnUrl = "http://localhost" . Yii::getAlias('@web/index.php/login/success'); $oauth->tokenUrl = 'https://api.fitbit.com/oauth2/token'; $oauth->fetchAccessToken($request->get('code'), [], $httpHeaders); $token = $oauth->getAccessToken(); $session->set('dump', $token); return $this->redirect('@web/index.php/site/dump'); }
/** * @inheritdoc */ protected function determineContentTypeByRaw($rawContent) { //determine json array's too if (preg_match('/^\\[.*\\]$/is', $rawContent)) { return self::CONTENT_TYPE_JSON; } return parent::determineContentTypeByRaw($rawContent); }
/** * @inheritdoc */ public function fetchAccessToken($authCode, array $params = []) { $authState = $this->getState('authState'); if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) { throw new HttpException(400, 'Invalid auth state parameter.'); } else { $this->removeState('authState'); } return parent::fetchAccessToken($authCode, $params); }
/** * Composes HTTP request CUrl options, which will be merged with the default ones. * @param string $method request type. * @param string $url request URL. * @param array $params request params. * @return array CUrl options. * @throws Exception on failure. */ protected function composeRequestCurlOptions($method, $url, array $params) { if ($method == 'CUSTOM_POST') { $curlOptions = []; $curlOptions[CURLOPT_POST] = true; $curlOptions[CURLOPT_POSTFIELDS] = implode('&', $params); return $curlOptions; } else { return parent::composeRequestCurlOptions($method, $url, $params); } }
public function init() { if ($this->debug) { $this->tokenUrl = self::URI_SANDBOX . $this->tokenUrl; $this->authUrl = self::URI_AUTHORIZE_SANDBOX . $this->authUrl; } else { $this->tokenUrl = self::URI_LIVE . $this->tokenUrl; $this->authUrl = self::URI_AUTHORIZE_LIVE . $this->authUrl; } return parent::init(); }
/** * @return OAuthToken auth token instance. * @throws QqExmailException */ public function getAccessToken() { $accessToken = parent::getAccessToken(); if (null === $accessToken || !$accessToken->getIsValid()) { $accessToken = $this->fetchAccessToken(); } if (null === $accessToken) { throw new QqExmailException('getAccessToken Fail.'); } return $accessToken; }
/** * @inheritdoc */ protected function apiInternal($accessToken, $url, $method, array $params, array $headers) { $params["application_key"] = $this->publicKey; if (ksort($params)) { $requestStr = ""; foreach ($params as $key => $value) { $requestStr .= $key . "=" . $value; } $requestStr .= md5($accessToken->getToken() . $this->clientSecret); $params['sig'] = md5($requestStr); } return parent::apiInternal($accessToken, $url, $method, $params, $headers); }
/** * Fetches the access token using the authorization code * @author Adegoke Obasa <*****@*****.**> * @param $code * @return mixed Access token * @throws Oauth2ClientException */ public function fetchAccessToken($code) { $this->validateTokenParams(); $this->oauth2->tokenUrl = $this->tokenUrl; $this->oauth2->clientId = $this->clientId; $this->oauth2->clientSecret = $this->clientSecret; try { $response = $this->oauth2->fetchAccessToken($code); } catch (Exception $ex) { throw new Oauth2ClientException($ex->getMessage()); } return $this->handleTokenResponse($response); }
/** * @inheritdoc */ protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO) { if ($contentType == self::CONTENT_TYPE_AUTO) { if (strpos($rawResponse, "callback") === 0) { $lpos = strpos($rawResponse, "("); $rpos = strrpos($rawResponse, ")"); $rawResponse = substr($rawResponse, $lpos + 1, $rpos - $lpos - 1); $rawResponse = trim($rawResponse); $contentType = self::CONTENT_TYPE_JSON; } } return parent::processResponse($rawResponse, $contentType); }
/** * Inits Urls based on $site */ public function init() { parent::init(); if (!$this->site) { $this->site = 'hi3a.hipanel.com'; } if (strpos($this->site, '://') === false) { $this->site = 'https://' . $this->site; } $defaults = ['authUrl' => 'oauth/authorize', 'tokenUrl' => 'oauth/token', 'apiBaseUrl' => 'api']; foreach ($defaults as $k => $v) { if (!$this->{$k}) { $this->{$k} = $this->buildUrl($v); } } }
/** * @return boolean */ public function disconnect() { $this->service->setAccessToken(new OAuthToken()); return !$this->isConnected(); }
/** * {@inheritdoc} */ public function buildAuthUrl(array $params = []) { return parent::buildAuthUrl(array_merge(['state' => 'ignored'], $params)); }
protected function defaultCurlOptions() { $curl_options = parent::defaultCurlOptions(); $curl_options[CURLOPT_USERAGENT] = (empty($this->clientName) ? empty(Yii::$app->name) ? Yii::$app->id : Yii::$app->name : $this->clientName) . ' OAuth 2.0 Client'; return $curl_options; }
/** * Add curl headers * * @inheritdoc */ protected function composeRequestCurlOptions($method, $url, array $params) { $curlOptions = parent::composeRequestCurlOptions($method, $url, $params); // add HTTP Basic Authorization headers for getting access token if ($url == $this->tokenUrl) { $curlOptions[CURLOPT_HTTPHEADER][] = 'Authorization: Basic ' . base64_encode("{$params["client_id"]}:{$params["client_secret"]}"); } elseif (strpos($url, $this->apiBaseUrl) !== false) { $curlOptions[CURLOPT_HTTPHEADER][] = 'Authorization: Bearer ' . $params['access_token']; } return $curlOptions; }
public function api($apiSubUrl, $method = 'GET', array $params = [], array $headers = []) { $params['method'] = $apiSubUrl; return parent::api($this->apiBaseUrl, $method, $params, $headers); }
/** * Creates token from its configuration. * @param array $tokenConfig token configuration. * @return OAuthToken token instance. */ protected function createToken(array $tokenConfig = []) { $tokenConfig['tokenParamKey'] = 'access_token'; return parent::createToken($tokenConfig); }
/** * Performs OAuth2 auth flow. * @param OAuth2 $client auth client instance. * @return Response action response. * @throws \yii\base\Exception on failure. */ protected function authOAuth2($client) { if (isset($_GET['error'])) { if ($_GET['error'] == 'access_denied') { // user denied error return $this->redirectCancel(); } else { // request error if (isset($_GET['error_description'])) { $errorMessage = $_GET['error_description']; } elseif (isset($_GET['error_message'])) { $errorMessage = $_GET['error_message']; } else { $errorMessage = http_build_query($_GET); } throw new Exception('Auth error: ' . $errorMessage); } } // Get the access_token and save them to the session. if (isset($_GET['code'])) { $code = $_GET['code']; $token = $client->fetchAccessToken($code); if (!empty($token)) { return $this->authSuccess($client); } else { return $this->redirectCancel(); } } else { $url = $client->buildAuthUrl(); return Yii::$app->getResponse()->redirect($url); } }
/** * Initialize this OAuth component */ public function init() { parent::init(); $view = Yii::$app->getView(); AuthChoiceStyleAsset::register($view); }
/** * @inheritdoc */ public function fetchAccessToken($authCode, array $params = []) { $authState = $this->getState('authState'); // if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) { // throw new HttpException(400, 'Invalid auth state parameter.'); // } else { // $this->removeState('authState'); // } $params['appid'] = $this->clientId; $params['secret'] = $this->clientSecret; return parent::fetchAccessToken($authCode, $params); }
public function init() { parent::init(); JWT::$leeway = $this->leeway; self::$_instance = $this; }
/** * @param string $rawResponse * @param string $contentType * @return array * @throws \yii\base\Exception */ protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO) { $contentType = self::CONTENT_TYPE_JSON; return parent::processResponse($rawResponse, $contentType); }