OAuth2 認証後、ユーザー情報提供エンドポイント
[POST] /api/varify/client
@ApiDoc(
description="validate client id/client secret/client token and retrive user id",
)
163264
public function postClientAction(Request $request)
    {
        $token = $this->get('security.token_storage')->getToken();

        $params = array();
        $content = $request->getContent();
        if (!empty($content))
        {
            $params = json_decode($content, true); // 2nd param to get as array
        }
        $client_id = $params['client_id'];
        $client_secret = $params['client_secret'];
        $access_token = $params['access_token'];


        if(! $client_id || ! $client_secret || ! $access_token)
        {
            return ['result' => false
                , 'err' => '0'
                , 'err_msg' => 'invalid parameter'
            ];
        }

        $user = $this->findByClientAndToken($access_token, $client_id, $client_secret);
        if(! $user ) {
            return [
                'result' => false
                , 'err' => '0'
                , 'err_msg' => 'user not found'
            ];
        } else if (time() > $user['expiresAt']){
            return [
                'result' => false
                , 'err' => '0'
                , 'err_msg' => 'token expired.'
            ];
        } else {
            return [
                'result' => true
                , 'user_id' => $user['id']
                , 'expires_at' => $user['expiresAt']
            ];
        }
    }
593633
public function curlPostAccessToken($oauth_verifier, $proxy = '') {
        $oauth_verifier = self::validateString('$oauth_verifier', $oauth_verifier);
        $proxy          = self::validateString('$proxy', $proxy);
        $url    = 'https://api.twitter.com/oauth/access_token';
        $params = compact('oauth_verifier');
        $ch     = self::curlInit($proxy);
        curl_setopt_array($ch, array(
            CURLOPT_HTTPHEADER => $this->getAuthorization($url, 'POST', $params, self::MODE_ACCESS_TOKEN),
            CURLOPT_URL        => $url,
            CURLOPT_POSTFIELDS => http_build_query($params, '', '&'),
            CURLOPT_POST       => true,
        ));
        return $ch;
    }
196571
private function validateAuthorizationCode(
        $authCodePayload,
        ClientEntityInterface $client,
        ServerRequestInterface $request
    ) {
        if (time() > $authCodePayload->expire_time) {
            throw OAuthServerException::invalidRequest('code', 'Authorization code has expired');
        }

        if ($this->authCodeRepository->isAuthCodeRevoked($authCodePayload->auth_code_id) === true) {
            throw OAuthServerException::invalidRequest('code', 'Authorization code has been revoked');
        }

        if ($authCodePayload->client_id !== $client->getIdentifier()) {
            throw OAuthServerException::invalidRequest('code', 'Authorization code was not issued to this client');
        }

        // The redirect URI is required in this request
        $redirectUri = $this->getRequestParameter('redirect_uri', $request, null);
        if (empty($authCodePayload->redirect_uri) === false && $redirectUri === null) {
            throw OAuthServerException::invalidRequest('redirect_uri');
        }

        if ($authCodePayload->redirect_uri !== $redirectUri) {
            throw OAuthServerException::invalidRequest('redirect_uri', 'Invalid redirect URI');
        }
    }
870850
public function authenticate(){
		$result = false;
		bimport('http.request');
		$code=BRequest::GetString('code');
		if(!isset($code)) {
			BLog::addToLog('[Social.FB] Code is empty!',LL_ERROR);
			return false;
			}
		$params = array(
			'client_id'	=> $this->clientId,
			'redirect_uri'  => $this->redirectUri,
//			'state'		=> 
			'client_secret' => $this->clientSecret,
			'code'	        => $code
			);
		parse_str($this->get('https://graph.facebook.com/oauth/access_token', $params, false), $tokenInfo);
		if(empty($tokenInfo)){
			BLog::addToLog('[Social.FB] tokenInfo is empty!',LL_ERROR);
			return false;
			}
		if(!isset($tokenInfo['access_token'])) {
			BLog::addToLog('[Social.FB] Access token is not set!',LL_ERROR);
			BLog::addToLog('[Social.FB] tokenInfo="'.var_export($tokenInfo,true).'".',LL_ERROR);
			return false;
			}
		$this->access_token=$tokenInfo['access_token'];
		$params = array('access_token' => $this->access_token,'fields' => 'id,name,email,birthday,gender');
		$userInfo = $this->get('https://graph.facebook.com/me', $params);
		if(!isset($userInfo['id'])) {
			BLog::addToLog('[Social.FB] userInfo id is not set!',LL_ERROR);
			BLog::addToLog('[Social.FB] userInfo="'.var_export($userInfo,true).'".',LL_ERROR);
			return false;
			}
		BLog::addToLog('[Social.FB] Got social info: '.var_export($userInfo,true));
		$this->userInfo = $userInfo;
		//
		if(!$this->createsession()){
			BLog::addToLog('[Social.FB] Could not create session!',LL_ERROR);
			return false;
			}
		BLog::addToLog('[Social.FB] All done!');
		return true;
		}
186110
public function authenticate(){
		bimport('http.request');
		$code=BRequest::GetString('code');
		if(empty($code)) {
			return false;
			}
		$params = array(
			'client_id'	 => $this->clientId,
			'client_secret' => $this->clientSecret,
			'redirect_uri'  => $this->redirectUri,
			'grant_type'	=> 'authorization_code',
			'code'		  => $code
			);
		$tokenInfo = $this->post('https://accounts.google.com/o/oauth2/token', $params);

		if(!isset($tokenInfo['access_token'])) {
			return false;
			}
		$params['access_token'] = $tokenInfo['access_token'];
		$userInfo = $this->get('https://www.googleapis.com/oauth2/v1/userinfo', $params);
		if(!isset($userInfo[$this->socialFieldsMap['socialId']])) {
			BLog::addToLog('[Social.Google] userInfo socialId is not set!',LL_ERROR);
			BLog::addToLog('[Social.Google] userInfo="'.var_export($userInfo,true).'".',LL_ERROR);
			return false;
			}
		$this->userInfo = $userInfo;
		//
		if(!$this->createsession()){
			BLog::addToLog('[Social.Google] Could not create session!',LL_ERROR);
			return false;
			}
		BLog::addToLog('[Social.Google] All done!');
		return true;

		}
711031
def _authenticate_client(self, client, secret):
        
        client_s = str.join(':', [client, secret])
        credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')

        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'no-cache',
            'Authorization': 'Basic ' + credentials
            }
        params = {
            'client_id': client,
            'grant_type': 'client_credentials'
            }
        uri = self.uri + '/oauth/token'

        logging.debug("URI=" + str(uri))
        logging.debug("HEADERS=" + str(headers))
        logging.debug("BODY=" + str(params))

        response = requests.post(uri, headers=headers, params=params)
        if response.status_code == 200:
            logging.debug("RESPONSE=" + str(response.json()))
            return response.json()
        else:
            logging.warning("Failed to authenticate as %s" % (client))
            response.raise_for_status()
686469
def get_access_token(client_id, client_secret):
	'''
	
	'''

	headers = {'Content-Type': 'application/x-www-form-urlencoded'}
	payload = {
		'client_id': client_id,
		'client_secret': client_secret
	}

	request = requests.post(token_url, data=payload, headers=headers)
	if request.status_code == 200:
		token = request.json()
		return token

	return {'status': request.status_code, "message": request.text}
233359
protected function get_access_token_params( $code, $client_id, $client_secret ) {
		return $this->filter_access_token_params( [
			'code'          => $code,
			'redirect_uri'  => $this->apply_filters( $this->get_service_name() . '_oauth_redirect_uri' ),
			'client_id'     => $client_id,
			'client_secret' => $client_secret,
		], $code, $client_id, $client_secret );
	}
1228101
public function checkClientCredentials($client_id, $client_secret = null)
    {
        if ($result = $this->getObjectByType('client_table',$client_id)) {
            return $result['client_secret'] == $client_secret;
        }

        return false;
    }
1082245
public function authenticate()
	{
		if ($data['code'] = $this->input->get('code', false, 'raw'))
		{
			$data['grant_type'] = 'authorization_code';
			$data['redirect_uri'] = $this->getOption('redirecturi');
			$data['client_id'] = $this->getOption('clientid');
			$data['client_secret'] = $this->getOption('clientsecret');
			$response = $this->http->post($this->getOption('tokenurl'), $data);

			if ($response->code >= 200 && $response->code < 400)
			{
				if ($response->headers['Content-Type'] == 'application/json')
				{
					$token = array_merge(json_decode($response->body, true), array('created' => time()));
				}
				else
				{
					parse_str($response->body, $token);
					$token = array_merge($token, array('created' => time()));
				}

				$this->setToken($token);

				return $token;
			}
			else
			{
				throw new \RuntimeException('Error code ' . $response->code . ' received requesting access token: ' . $response->body . '.');
			}
		}

		if ($this->getOption('sendheaders'))
		{
			$this->application->redirect($this->createUrl());
		}

		return false;
	}
432731
private function generateRequestToken()
	{
		// Set the callback URL.
		if ($this->getOption('callback'))
		{
			$parameters = array(
				'oauth_callback' => $this->getOption('callback'),
			);
		}
		else
		{
			$parameters = array();
		}

		// Make an OAuth request for the Request Token.
		$response = $this->oauthRequest($this->getOption('requestTokenURL'), 'POST', $parameters);

		parse_str($response->body, $params);

		if (strcmp($this->version, '1.0a') === 0 && strcmp($params['oauth_callback_confirmed'], 'true') !== 0)
		{
			throw new \DomainException('Bad request token!');
		}

		// Save the request token.
		$this->token = array('key' => $params['oauth_token'], 'secret' => $params['oauth_token_secret']);

		// Save the request token in session
		$session = $this->application->getSession();
		$session->set('oauth_token.key', $this->token['key']);
		$session->set('oauth_token.secret', $this->token['secret']);
	}
735452
function OAuth2Error(message, code, uri, status) {
  Error.call(this);
  this.message = message;
  this.code = code || 'server_error';
  this.uri = uri;
  this.status = status || 500;
}
996080
public function curlPostRequestToken($oauth_callback = '', $proxy = '') {
        $oauth_callback = self::validateString('$oauth_callback', $oauth_callback);
        $proxy          = self::validateString('$proxy', $proxy);
        $url    = 'https://api.twitter.com/oauth/request_token';
        $params = compact('oauth_callback');
        $ch     = self::curlInit($proxy);
        curl_setopt_array($ch, array(
            CURLOPT_HTTPHEADER => $this->getAuthorization($url, 'POST', $params, self::MODE_REQUEST_TOKEN),
            CURLOPT_URL        => $url,
            CURLOPT_POSTFIELDS => http_build_query($params, '', '&'),
            CURLOPT_POST       => true,
        ));
        return $ch;
    }
583557
private function _authHeader(): string
    {
        if (empty($this->_client_id)) {
            throw new VimeoException('A client ID must be set in order to generate an auth header.');
        } elseif (empty($this->_client_secret)) {
            throw new VimeoException('A client secret must be set in order to generate an auth header.');
        }

        return base64_encode($this->_client_id . ':' . $this->_client_secret);
    }
292305
def oauth_query
      {
        client_id:     client_id,
        scope:         scope,
        response_type: "code",
        redirect_uri:  redirect_uri
      }.map do |key, val|
        "#{CGI.escape(key.to_s)}=#{CGI.escape(val.to_s)}"
      end.join(?&)
    end
333553
function oAuthRequest($url, $method, $parameters, $multi = false) {

    if (strrpos($url, 'http://') !== 0 && strrpos($url, 'https://') !== 0) {
      $url = "{$this->host}{$url}.{$this->format}";
  }

  switch ($method) {
    case 'GET':
      $url = $url . '?' . http_build_query($parameters);
      return $this->http($url, 'GET');
    default:
      $headers = array();
      if (!$multi && (is_array($parameters) || is_object($parameters)) ) {
        $body = http_build_query($parameters);
      } else {
        $body = self::build_http_query_multi($parameters);
        $headers[] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
      }
      return $this->http($url, $method, $body, $headers);
  }
  }
249965
public function accessToken(){
		$url = 'https://api.dropbox.com/1/oauth/access_token';
		$result = $this->doOAuthCall($url,'POST');
		parse_str($result['body'], $output);
		if (!count(array_diff(array('oauth_token','oauth_token_secret','uid'),
			array_keys($output))))
		{
			$this->setAuthToken($output['oauth_token'], $output['oauth_token_secret']);
			return $output;
		} else {
			$result = json_decode($result['body'], true);
			trigger_error(sprintf(self::E_AUTHERROR, $result['error']));
			return false;
		}
	}