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
См. также: http://oauth.net/2/
См. также: https://tools.ietf.org/html/rfc6749
С версии: 2.0
Автор: Paul Klimov (klimov.paul@gmail.com)
Наследование: extends BaseOAuth
Пример #1
1
 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!');
 }
Пример #2
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->scope === null) {
         $this->scope = implode(' ', ['profile', 'email']);
     }
 }
Пример #3
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->scope === null) {
         $this->scope = implode(' ', ['r_basicprofile', 'r_emailaddress']);
     }
 }
Пример #4
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->scope === null) {
         $this->scope = 'user';
     }
 }
Пример #5
0
 /**
  * @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']);
     }
 }
Пример #6
0
 /**
  * @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);
 }
Пример #7
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->scope === null) {
         $this->scope = implode(' ', ['user', 'user:email']);
     }
 }
Пример #8
0
Файл: Live.php Проект: howq/yii2
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->scope === null) {
         $this->scope = implode(',', ['wl.basic', 'wl.emails']);
     }
 }
Пример #9
0
 public function init()
 {
     parent::init();
     if ($this->scope === null) {
         $this->scope = implode(',', ['get_user_info']);
     }
 }
Пример #10
0
 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');
 }
Пример #11
0
 /**
  * @inheritdoc
  */
 protected function determineContentTypeByRaw($rawContent)
 {
     //determine json array's too
     if (preg_match('/^\\[.*\\]$/is', $rawContent)) {
         return self::CONTENT_TYPE_JSON;
     }
     return parent::determineContentTypeByRaw($rawContent);
 }
Пример #12
0
 /**
  * @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);
 }
Пример #13
0
 /**
  * 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);
     }
 }
Пример #14
0
 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();
 }
Пример #15
0
 /**
  * @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;
 }
Пример #16
0
 /**
  * @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);
 }
Пример #17
0
 /**
  * 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);
 }
Пример #18
0
 /**
  * @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);
 }
Пример #19
0
 /**
  * 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);
         }
     }
 }
Пример #20
0
 /**
  * @return boolean
  */
 public function disconnect()
 {
     $this->service->setAccessToken(new OAuthToken());
     return !$this->isConnected();
 }
Пример #21
0
 /**
  * {@inheritdoc}
  */
 public function buildAuthUrl(array $params = [])
 {
     return parent::buildAuthUrl(array_merge(['state' => 'ignored'], $params));
 }
Пример #22
0
 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;
 }
Пример #23
0
 /**
  * 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;
 }
Пример #24
0
 public function api($apiSubUrl, $method = 'GET', array $params = [], array $headers = [])
 {
     $params['method'] = $apiSubUrl;
     return parent::api($this->apiBaseUrl, $method, $params, $headers);
 }
Пример #25
0
 /**
  * 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);
 }
Пример #26
0
 /**
  * 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);
 }
Пример #28
0
 /**
  * @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);
 }
Пример #29
0
 public function init()
 {
     parent::init();
     JWT::$leeway = $this->leeway;
     self::$_instance = $this;
 }
Пример #30
0
 /**
  * @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);
 }