/** * Sign the request using OAuth. This uses the consumer token and key * but 2 legged oauth doesn't require an access token and key. In situations where you want to * do a 'reverse phone home' (aka: gadget does a makeRequest to your server * and your server wants to retrieve more social information) this is the prefered * method. * * @param string $method the method (get/put/delete/post) * @param string $url the url to sign (http://site/social/rest/people/1/@me) * @param array $params the params that should be appended to the url (count=20 fields=foo, etc) * @param string $postBody for POST/PUT requests, the postBody is included in the signature * @return string the signed url */ public function sign($method, $url, $params = array(), $postBody = false, &$headers = array()) { $oauthRequest = OAuthRequest::from_request($method, $url, $params); $params = $this->mergeParameters($params); foreach ($params as $key => $val) { if (is_array($val)) { $val = implode(',', $val); } $oauthRequest->set_parameter($key, $val); } if ($postBody && strlen($postBody)) { if ($this->useBodyHash) { $bodyHash = base64_encode(sha1($postBody, true)); $oauthRequest->set_parameter("oauth_body_hash", $bodyHash); } if ($this->useBodyHack) { $oauthRequest->set_parameter($postBody, ''); } } $oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken); if ($postBody && $this->useBodyHack) { unset($oauthRequest->parameters[$postBody]); } $signedUrl = $oauthRequest->to_url(); return $signedUrl; }
public function validate_request() { $result = true; // Is gadget_url specified? if (sizeof($this->gadget_url) > 0) { // Does gadget_url match opensocial_app_id? if ($this->opensocial_app_url != $this->gadget_url) { $result = false; } } // Is this a signed request? if (!empty($this->oauth_consumer_key) && !empty($this->oauth_signature)) { $request = OAuthRequest::from_request(null, null, array_merge($_GET, $_POST)); $signature_method = new ServerSignatureMethod(); $signature_method->set_public_cert($this->oauth_consumer_key); // See if signature is valid if (!$signature_method->check_signature($request, null, null, $this->oauth_signature)) { $result = false; } } else { $result = false; } // If invalid request, return HTTP 401 response if (!$result) { header("HTTP/1.0 401 Unauthorized", true, 401); echo "<html><body>401 Unauthorized</body></html>"; die; } // If valid request, go forward return true; }
/** * Handle a request for temporary OAuth credentials * * Make sure the request is kosher, then emit a set of temporary * credentials -- AKA an unauthorized request token. * * @param array $args array of arguments * * @return void */ function handle($args) { parent::handle($args); $datastore = new ApiStatusNetOAuthDataStore(); $server = new OAuthServer($datastore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($hmac_method); try { $req = OAuthRequest::from_request(); // verify callback if (!$this->verifyCallback($req->get_parameter('oauth_callback'))) { throw new OAuthException("You must provide a valid URL or 'oob' in oauth_callback.", 400); } // check signature and issue a new request token $token = $server->fetch_request_token($req); common_log(LOG_INFO, sprintf("API OAuth - Issued request token %s for consumer %s with oauth_callback %s", $token->key, $req->get_parameter('oauth_consumer_key'), "'" . $req->get_parameter('oauth_callback') . "'")); // return token to the client $this->showRequestToken($token); } catch (OAuthException $e) { common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage()); // Return 401 for for bad credentials or signature problems, // and 400 for missing or unsupported parameters $code = $e->getCode(); $this->clientError($e->getMessage(), empty($code) ? 401 : $code, 'text'); } }
public function execute($filterChain) { require_once 'OAuth.php'; $consumer = $token = null; try { $req = OAuthRequest::from_request(); list($consumer, $token) = $this->getServer()->verify_request($req); } catch (OAuthException $e) { // do nothing } if ($consumer) { sfContext::getInstance()->getUser()->setAuthenticated(true); $information = Doctrine::getTable('OAuthConsumerInformation')->findByKeyString($consumer->key); if ($information) { sfContext::getInstance()->getUser()->addCredentials($information->getUsingApis()); } $tokenType = $this->context->getRequest()->getParameter('token_type', 'member'); if ('member' === $tokenType) { $accessToken = Doctrine::getTable('OAuthMemberToken')->findByKeyString($token->key, 'access'); sfContext::getInstance()->getUser()->setAttribute('member_id', $accessToken->getMember()->id); } } $route = $this->context->getRequest()->getAttribute('sf_route'); if ($route instanceof opAPIRouteInterface) { $actionInstance = $this->context->getController()->getActionStack()->getLastEntry()->getActionInstance(); $config = $actionInstance->getSecurityConfiguration(); if (!isset($config['all']['credentials'])) { $config['all']['credentials'] = array(); } $config['all']['credentials'] = array_merge($config['all']['credentials'], array($route->getAPIName())); $actionInstance->setSecurityConfiguration($config); } $filterChain->execute(); }
/** * Class handler. * * @param array $args array of arguments * * @return void */ function handle($args) { parent::handle($args); $datastore = new ApiStatusNetOAuthDataStore(); $server = new OAuthServer($datastore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($hmac_method); $atok = $app = null; // XXX: Insist that oauth_token and oauth_verifier be populated? // Spec doesn't say they MUST be. try { $req = OAuthRequest::from_request(); $this->reqToken = $req->get_parameter('oauth_token'); $this->verifier = $req->get_parameter('oauth_verifier'); $app = $datastore->getAppByRequestToken($this->reqToken); $atok = $server->fetch_access_token($req); } catch (Exception $e) { common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage()); common_debug(var_export($req, true)); $code = $e->getCode(); $this->clientError($e->getMessage(), empty($code) ? 401 : $code, 'text'); return; } if (empty($atok)) { // Token exchange failed -- log it $msg = sprintf('API OAuth - Failure exchanging OAuth request token for access token, ' . 'request token = %s, verifier = %s', $this->reqToken, $this->verifier); common_log(LOG_WARNING, $msg); // TRANS: Client error given from the OAuth API when the request token or verifier is invalid. $this->clientError(_('Invalid request token or verifier.'), 400, 'text'); } else { common_log(LOG_INFO, sprintf("Issued access token '%s' for application %d (%s).", $atok->key, $app->id, $app->name)); $this->showAccessToken($atok); } }
function brukar_server_oauth_user() { $server = _brukar_server(); $request = OAuthRequest::from_request(); list($consumer, $token) = $server->verify_request($request); $user = user_load($token->uid); echo json_encode(array('id' => $user->uid, 'name' => $user->name, 'mail' => $user->mail)); exit; }
static public function listenToPreActionEventOauthAccessToken(sfEvent $event) { $action = $event['actionInstance']; $request = sfContext::getInstance()->getRequest(); if (!$request->hasParameter('x_auth_mode')) { return; } if ($request->getParameter('x_auth_mode') !== 'client_auth') { return; } $params = $request->getPostParameters(); unset($params['x_auth_mode']); $formParams = array(); foreach ($params as $key => $value) { if (strpos($key, 'x_auth_') === 0) { $formParams[mb_substr($key, 7)] = $value; } } $authForm = sfContext::getInstance()->getUser()->getAuthForm(); $authForm->disableCSRFProtection(); $authForm->bind($formParams); if (!$authForm->isValid()) { return; } // request token $authRequest = OAuthRequest::from_request(); $token = opXAuthPluginToolkit::getServer($action)->fetch_request_token($authRequest); // authorize token $information = opXAuthPluginToolkit::getTokenTable()->findByKeyString($token->key); $action->forward404Unless($information); $callback = $authRequest->get_parameter('oauth_callback'); $information->setCallbackUrl($callback ? $callback : 'oob'); $information->setMemberId(sfContext::getInstance()->getUser()->getMemberId()); $information->save(); // accsess token $consumer = new OAuthConsumer($authRequest->get_parameter('oauth_consumer_key')); $token = opXAuthPluginToolkit::getDataStore()->new_access_token($token, $consumer); echo (string)$token; exit; }
function handleOAuthBodyPOST($oauth_consumer_key, $oauth_consumer_secret) { $request_headers = OAuthUtil::get_headers(); // print_r($request_headers); // Must reject application/x-www-form-urlencoded if ($request_headers['Content-type'] == 'application/x-www-form-urlencoded' ) { throw new Exception("OAuth request body signing must not use application/x-www-form-urlencoded"); } if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") { $header_parameters = OAuthUtil::split_header($request_headers['Authorization']); // echo("HEADER PARMS=\n"); // print_r($header_parameters); $oauth_body_hash = $header_parameters['oauth_body_hash']; // echo("OBH=".$oauth_body_hash."\n"); } if ( ! isset($oauth_body_hash) ) { throw new Exception("OAuth request body signing requires oauth_body_hash body"); } // Verify the message signature $store = new TrivialOAuthDataStore(); $store->add_consumer($oauth_consumer_key, $oauth_consumer_secret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); global $LastOAuthBodyBaseString; $LastOAuthBodyBaseString = $request->get_signature_base_string(); // echo($LastOAuthBodyBaseString."\n"); try { $server->verify_request($request); } catch (Exception $e) { $message = $e->getMessage(); throw new Exception("OAuth signature failed: " . $message); } $postdata = file_get_contents('php://input'); // echo($postdata); $hash = base64_encode(sha1($postdata, TRUE)); if ( $hash != $oauth_body_hash ) { throw new Exception("OAuth oauth_body_hash mismatch"); } return $postdata; }
/** * Exchange the request token for an access token * * Endpoint: /auth/access_token */ public static function access_token() { try { $request = OAuthRequest::from_request(); $result = WPOAuthProvider::access_token($request); header('Content-Type: application/x-www-form-urlencoded'); echo $result; } catch (OAuthException $e) { throw new Exception($e->getMessage(), 401); } }
function api_content(&$a) { if ($a->cmd == 'api/oauth/authorize') { /* * api/oauth/authorize interact with the user. return a standard page */ $a->page['template'] = "minimal"; // get consumer/client from request token try { $request = OAuthRequest::from_request(); } catch (Exception $e) { echo "<pre>"; var_dump($e); killme(); } if (x($_POST, 'oauth_yes')) { $app = oauth_get_client($request); if (is_null($app)) { return "Invalid request. Unknown token."; } $consumer = new OAuthConsumer($app['client_id'], $app['pw'], $app['redirect_uri']); $verifier = md5($app['secret'] . local_channel()); set_config("oauth", $verifier, local_channel()); if ($consumer->callback_url != null) { $params = $request->get_parameters(); $glue = "?"; if (strstr($consumer->callback_url, $glue)) { $glue = "?"; } goaway($consumer->callback_url . $glue . "oauth_token=" . OAuthUtil::urlencode_rfc3986($params['oauth_token']) . "&oauth_verifier=" . OAuthUtil::urlencode_rfc3986($verifier)); killme(); } $tpl = get_markup_template("oauth_authorize_done.tpl"); $o = replace_macros($tpl, array('$title' => t('Authorize application connection'), '$info' => t('Return to your app and insert this Securty Code:'), '$code' => $verifier)); return $o; } if (!local_channel()) { //TODO: we need login form to redirect to this page notice(t('Please login to continue.') . EOL); return login(false, 'api-login', $request->get_parameters()); } //FKOAuth1::loginUser(4); $app = oauth_get_client($request); if (is_null($app)) { return "Invalid request. Unknown token."; } $tpl = get_markup_template('oauth_authorize.tpl'); $o = replace_macros($tpl, array('$title' => t('Authorize application connection'), '$app' => $app, '$authorize' => t('Do you want to authorize this application to access your posts and contacts, and/or create new posts for you?'), '$yes' => t('Yes'), '$no' => t('No'))); //echo "<pre>"; var_dump($app); killme(); return $o; } echo api_call($a); killme(); }
/** * Class handler. * * @param array $args array of arguments * * @return void */ function handle($args) { parent::handle($args); try { common_remove_magic_from_request(); $req = OAuthRequest::from_request(); $server = omb_oauth_server(); $token = $server->fetch_request_token($req); print $token; } catch (OAuthException $e) { $this->serverError($e->getMessage()); } }
public function executeAccessToken(sfWebRequest $request) { require_once 'OAuth.php'; $requestToken = $request->getParameter('oauth_token'); $this->information = $this->getTokenTable()->findByKeyString($requestToken); $this->forward404Unless($this->information); $this->forward404Unless($this->information->getIsActive()); $this->forward404Unless($this->information->getVerifier() === $request->getParameter('oauth_verifier')); $authRequest = OAuthRequest::from_request(); $token = $this->getServer()->fetch_access_token($authRequest); $this->information->delete(); $this->getResponse()->setContent((string) $token); return sfView::NONE; }
public function authorize($params) { if (!isset($_SESSION['id'])) { header("Location: /login?redirect=" . urlencode($_SERVER['REQUEST_URI'])); die; } $request = OAuthRequest::from_request(); $token = $request->get_parameter('oauth_token'); $callback = $request->get_parameter('oauth_callback'); if (!$token) { $this->sendServerError('400', 'Bad Request - missing oauth_token'); return; } $this->template('oauth/authorize.php', array('oauth_token' => $token, 'oauth_callback' => $callback)); }
function handle($args) { parent::handle($args); try { common_remove_magic_from_request(); $req = OAuthRequest::from_request(); # Note: server-to-server function! $server = omb_oauth_server(); list($consumer, $token) = $server->verify_request($req); if ($this->save_notice($req, $consumer, $token)) { print "omb_version=" . OMB_VERSION_01; } } catch (OAuthException $e) { $this->serverError($e->getMessage()); return; } }
/** * Class handler. * * @param array $args array of arguments * * @return void */ function handle($args) { parent::handle($args); $datastore = new ApiStatusNetOAuthDataStore(); $server = new OAuthServer($datastore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($hmac_method); try { $req = OAuthRequest::from_request(); $token = $server->fetch_request_token($req); print $token; } catch (OAuthException $e) { common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage()); header('HTTP/1.1 401 Unauthorized'); header('Content-Type: text/html; charset=utf-8'); print $e->getMessage() . "\n"; } }
/** * Class handler. * * @param array $args query arguments * * @return boolean false if user doesn't exist */ function handle($args) { parent::handle($args); try { common_debug('getting request from env variables', __FILE__); common_remove_magic_from_request(); $req = OAuthRequest::from_request(); common_debug('getting a server', __FILE__); $server = omb_oauth_server(); common_debug('fetching the access token', __FILE__); $token = $server->fetch_access_token($req); common_debug('got this token: "' . print_r($token, true) . '"', __FILE__); common_debug('printing the access token', __FILE__); print $token; } catch (OAuthException $e) { $this->serverError($e->getMessage()); } }
public function getSecurityToken() { // see if we have an OAuth request $request = OAuthRequest::from_request(); $appUrl = $request->get_parameter('oauth_consumer_key'); $userId = $request->get_parameter('xoauth_requestor_id'); // from Consumer Request extension (2-legged OAuth) $signature = $request->get_parameter('oauth_signature'); if ($appUrl && $signature) { //if ($appUrl && $signature && $userId) { // look up the user and perms for this oauth request $oauthLookupService = Config::get('oauth_lookup_service'); $oauthLookupService = new $oauthLookupService(); $token = $oauthLookupService->getSecurityToken($request, $appUrl, $userId); if ($token) { return $token; } else { return null; // invalid oauth request, or 3rd party doesn't have access to this user } } // else, not a valid oauth request, so don't bother // look for encrypted security token $token = isset($_POST['st']) ? $_POST['st'] : (isset($_GET['st']) ? $_GET['st'] : ''); if (empty($token)) { if (Config::get('allow_anonymous_token')) { // no security token, continue anonymously, remeber to check // for private profiles etc in your code so their not publicly // accessable to anoymous users! Anonymous == owner = viewer = appId = modId = 0 // create token with 0 values, no gadget url, no domain and 0 duration //FIXME change this to a new AnonymousToken when reworking auth token $gadgetSigner = Config::get('security_token'); return new $gadgetSigner(null, 0, 0, 0, 0, '', '', 0); } else { return null; } } if (count(explode(':', $token)) != 6) { $token = urldecode(base64_decode($token)); } $gadgetSigner = Config::get('security_token_signer'); $gadgetSigner = new $gadgetSigner(); return $gadgetSigner->createToken($token); }
public function getSecurityToken() { // Support a configurable host name ('http_host' key) so that OAuth signatures don't fail in reverse-proxy type situations $scheme = !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on" ? 'http' : 'https'; $http_url = $scheme . '://' . (Config::get('http_host') ? Config::get('http_host') : $_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI']; // see if we have an OAuth request $request = OAuthRequest::from_request(null, $http_url, null); $appUrl = $request->get_parameter('oauth_consumer_key'); $userId = $request->get_parameter('xoauth_requestor_id'); // from Consumer Request extension (2-legged OAuth) $signature = $request->get_parameter('oauth_signature'); if ($appUrl && $signature) { //if ($appUrl && $signature && $userId) { // look up the user and perms for this oauth request $oauthLookupService = Config::get('oauth_lookup_service'); $oauthLookupService = new $oauthLookupService(); $token = $oauthLookupService->getSecurityToken($request, $appUrl, $userId, $this->getContentType()); if ($token) { $token->setAuthenticationMode(AuthenticationMode::$OAUTH_CONSUMER_REQUEST); return $token; } else { return null; // invalid oauth request, or 3rd party doesn't have access to this user } } // else, not a valid oauth request, so don't bother // look for encrypted security token $token = isset($_POST['st']) ? $_POST['st'] : (isset($_GET['st']) ? $_GET['st'] : ''); if (empty($token)) { if (Config::get('allow_anonymous_token')) { // no security token, continue anonymously, remeber to check // for private profiles etc in your code so their not publicly // accessable to anoymous users! Anonymous == owner = viewer = appId = modId = 0 // create token with 0 values, no gadget url, no domain and 0 duration $gadgetSigner = Config::get('security_token'); return new $gadgetSigner(null, 0, SecurityToken::$ANONYMOUS, SecurityToken::$ANONYMOUS, 0, '', '', 0, Config::get('container_id')); } else { return null; } } $gadgetSigner = Config::get('security_token_signer'); $gadgetSigner = new $gadgetSigner(); return $gadgetSigner->createToken($token); }
/** * Create new Basic LTI access object * * @param string $key * @param string $secret * * @throws \Exception */ public function __construct($key, $secret) { $request = \OAuthRequest::from_request(); $oauth_consumer_key = $request->get_parameter("oauth_consumer_key"); // ensure the key in the request matches the locally supplied one if ($oauth_consumer_key == null) { throw new \Exception("Missing oauth_consumer_key in request"); } if ($oauth_consumer_key != $key) { throw new \Exception("oauth_consumer_key doesn't match supplied key"); } // verify the message signature $store = new TrivialOAuthDataStore($oauth_consumer_key, $secret); $server = new \OAuthServer($store); $method = new \OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $server->verify_request($request); $this->request = $request; }
function handle($args) { parent::handle($args); try { common_remove_magic_from_request(); $req = OAuthRequest::from_request(); # Note: server-to-server function! $server = omb_oauth_server(); list($consumer, $token) = $server->verify_request($req); if ($this->update_profile($req, $consumer, $token)) { header('HTTP/1.1 200 OK'); header('Content-type: text/plain'); print "omb_version=" . OMB_VERSION_01; } } catch (OAuthException $e) { $this->serverError($e->getMessage()); return; } }
function authenticate() { $request = OAuthRequest::from_request(); $consumer_key = $request->get_parameter('oauth_consumer_key'); $signature_method = $request->get_parameter('oauth_signature_method'); $signature = $request->get_parameter('oauth_signature'); if ($signature_method === "HMAC-SHA1") { $sm = new OAuthSignatureMethod_HMAC_SHA1(); $stmt = $this->db->prepare('SELECT consumerSecret FROM storageConsumers WHERE consumerKey = :key'); $stmt->bindParam(':key', $consumer_key); $stmt->execute(); $row = $stmt->fetch(); if ($row === FALSE || empty($row)) { throw new Exception("consumer not found"); } $consumer_secret = $row['consumerSecret']; $valid = $sm->check_signature($request, new OAuthConsumer($consumer_key, $consumer_secret), NULL, $signature); } else { if ($signature_method === "RSA-SHA1") { $sm = new MyOAuthSignatureMethod_RSA_SHA1($this->db); $valid = $sm->check_signature($request, NULL, NULL, $signature); } else { throw new Exception("invalid signature method"); } } if (!$valid) { throw new Exception("invalid signature"); } else { /* SURFconext (contains groupContext) */ $instance_id = $request->get_parameter('opensocial_instance_id'); /* iGoogle and other OpenSocial/Shindig portals/containers */ $owner_id = $request->get_parameter('opensocial_owner_id'); if ($instance_id !== NULL) { $this->consumerKey = $consumer_key . '_' . $instance_id; } else { if ($owner_id !== NULL) { $this->consumerKey = $consumer_key . '_' . $owner_id; } else { $this->consumerKey = $consumer_key; } } } }
/** * Sign the request using OAuth. This uses the consumer token and key * but 2 legged oauth doesn't require an access token and key. In situations where you want to * do a 'reverse phone home' (aka: gadget does a makeRequest to your server * and your server wants to retrieve more social information) this is the prefered * method. * * @param string $method the method (get/put/delete/post) * @param string $url the url to sign (http://site/social/rest/people/1/@me) * @param array $params the params that should be appended to the url (count=20 fields=foo, etc) * @param string $postBody for POST/PUT requests, the postBody is included in the signature * @return string the signed url */ public function sign($method, $url, $params = array(), $postBody = false) { $oauthRequest = OAuthRequest::from_request($method, $url, $params); $params = $this->mergeParameters($params); foreach ($params as $key => $val) { if (is_array($val)) { $val = implode(',', $val); } $oauthRequest->set_parameter($key, $val); } if ($postBody && strlen($postBody)) { $oauthRequest->set_parameter($postBody, ''); } $oauthRequest->sign_request($this->signatureMethod, $this->consumerToken, $this->accessToken); if ($postBody) { unset($oauthRequest->parameters[$postBody]); } $signedUrl = $oauthRequest->to_url(); return $signedUrl; }
/** * Constructor * * Note that the person is tied to a OAuth datastore here */ function __construct($person = NULL) { parent::__construct($person); /* Find the path to simpelsamlphp and run the autoloader */ try { $sspdir = Config::get_config('simplesaml_path'); } catch (KeyNotFoundException $knfe) { echo "Cannot find path to simplesaml. This install is not valid. Aborting.<br />\n"; Logger::log_event(LOG_ALERT, "Trying to instantiate simpleSAMLphp without a configured path."); exit(0); } require_once $sspdir . '/lib/_autoload.php'; SimpleSAML_Configuration::setConfigDir($sspdir . '/config'); $this->oauthStore = new OAuthDataStore_Confusa(); $this->oauthServer = new sspmod_oauth_OAuthServer($this->oauthStore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $this->oauthServer->add_signature_method($hmac_method); $req = OAuthRequest::from_request(); list($consumer, $this->accessToken) = $this->oauthServer->verify_request($req); $this->isAuthenticated = isset($this->accessToken); }
public function executeAccessToken(sfWebRequest $request) { $req = OAuthRequest::from_request(NULL, $request->getUri()); // To get variable in header if ($req->get_parameter('oauth_version') == '1.0') { $oauthServer = new sfoauthserver(new sfOAuthDataStore()); $req = OAuthRequest::from_request(NULL, $request->getUri()); $q = Doctrine::getTable('sfOauthServerRequestToken')->findOneByToken($req->get_parameter('oauth_token')); $this->token = $oauthServer->fetch_access_token($req); if ($q->getUserId() == NULL && $q->getScope()) { throw new OAuthException('Token unauthorized'); } return $this->setTemplate('token'); } else { $q = Doctrine::getTable('sfOauthServerRequestToken')->findOneByToken($request->getParameter('code')); $oauthServer2 = new sfOauth2Server(); $oauthServer2->setUserId($q->getUserId()); $oauthServer2->grantAccessToken($q->getScope()); return sfView::NONE; } }
/** * Executes this filter. * * @param sfFilterChain $filterChain A sfFilterChain instance */ public function execute($filterChain) { //load oauth configuration $actionInstance = $this->context->getController()->getActionStack()->getLastEntry()->getActionInstance(); $sfoauth = new sfOauth($this->context, $actionInstance->getModuleName(), $actionInstance->getActionName()); $request = $this->context->getRequest(); $req = OAuthRequest::from_request(); SfContext::getInstance()->getLogger()->debug("Abans de comprovar la versió"); if ($req->get_parameter('oauth_version', NULL) == "1.0") { SfContext::getInstance()->getLogger()->debug("Versio 1.0"); $oauthServer = new sfoauthserver(new sfOAuthDataStore()); $oauthServer->verify_request($req); } else { if ($request->getParameter('oauth_version', NULL) != NULL) { throw new OAuthException('not supported version'); } else { SfContext::getInstance()->getLogger()->debug("No hi ha versio"); throw new OAuthException('oauth_version parameter missing'); } } SfContext::getInstance()->getLogger()->debug("Configura coses"); $token = $req->get_parameter('oauth_token'); $sfToken = Doctrine::getTable('sfOauthServerAccessToken')->findOneByToken($token); $user = $sfToken->getUser(); // Select user concerned $consumer = $sfToken->getConsumer(); $consumer->increaseNumberQuery(); $request->setParameter('sfGuardUser', $user); // save this user in a parameter 'user' $request->setParameter('sfOauthConsumer', $consumer); // save consumer in a parameter 'consumer' $credential = $sfoauth->getOauthCredential(); SfContext::getInstance()->getLogger()->debug("Acaba de configurar coses"); if (null !== $credential && !$sfToken->hasCredential($credential)) { throw new OAuthException('Unauthorized Access'); } // chek if the consumer is allowed to access to this action // this aplpication has access, continue $filterChain->execute(); }
protected function getMemberIdByOAuth() { require_once 'OAuth.php'; $consumer = $token = null; try { $req = OAuthRequest::from_request(); list($consumer, $token) = $this->getServer()->verify_request($req); } catch (OAuthException $e) { // do nothing } if ($consumer) { $information = Doctrine::getTable('OAuthConsumerInformation')->findByKeyString($consumer->key); if ($information) { $tokenType = $this->getRequest()->getParameter('token_type', 'member'); if ('member' === $tokenType) { $accessToken = Doctrine::getTable('OAuthMemberToken')->findByKeyString($token->key, 'access'); return $accessToken->getMemberId(); } } } $this->forward('saa', 'error401'); }
function handle_oauth_body_post($oauthconsumerkey, $oauthconsumersecret, $body, $requestheaders = null) { if ($requestheaders == null) { $requestheaders = OAuthUtil::get_headers(); } // Must reject application/x-www-form-urlencoded. if (isset($requestheaders['Content-type'])) { if ($requestheaders['Content-type'] == 'application/x-www-form-urlencoded') { throw new OAuthException("OAuth request body signing must not use application/x-www-form-urlencoded"); } } if (@substr($requestheaders['Authorization'], 0, 6) == "OAuth ") { $headerparameters = OAuthUtil::split_header($requestheaders['Authorization']); $oauthbodyhash = $headerparameters['oauth_body_hash']; } if (!isset($oauthbodyhash)) { throw new OAuthException("OAuth request body signing requires oauth_body_hash body"); } // Verify the message signature. $store = new TrivialOAuthDataStore(); $store->add_consumer($oauthconsumerkey, $oauthconsumersecret); $server = new OAuthServer($store); $method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($method); $request = OAuthRequest::from_request(); try { $server->verify_request($request); } catch (\Exception $e) { $message = $e->getMessage(); throw new OAuthException("OAuth signature failed: " . $message); } $postdata = $body; $hash = base64_encode(sha1($postdata, true)); if ($hash != $oauthbodyhash) { throw new OAuthException("OAuth oauth_body_hash mismatch"); } return $postdata; }
public function initFromRequest($realurl = null) { $request = OAuthRequest::from_request(null, $realurl); $token = null; if ($request->get_parameter('oauth_token') && $request->get_parameter('oauth_token_secret')) { $token = new OAuthToken($request->get_parameter('oauth_token'), $request->get_parameter('oauth_token_secret')); } switch ($request->get_parameter('auth_signature_method')) { default: case 'HMAC-SHA1': $sign_method = new OAuthSignatureMethod_HMAC_SHA1(); break; //case 'RSA-SHA1': // break; //case 'RSA-SHA1': // break; case 'PLAINTEXT': $sign_method = new OAuthSignatureMethod_PLAINTEXT(); break; } $this->from_request = $request; $this->token = $token; $this->sign_method = $sign_method; }
/** * Class handler. * * @param array $args array of arguments * * @return void */ function handle($args) { parent::handle($args); $datastore = new ApiStatusNetOAuthDataStore(); $server = new OAuthServer($datastore); $hmac_method = new OAuthSignatureMethod_HMAC_SHA1(); $server->add_signature_method($hmac_method); $atok = null; try { $req = OAuthRequest::from_request(); $atok = $server->fetch_access_token($req); } catch (OAuthException $e) { common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage()); common_debug(var_export($req, true)); $this->outputError($e->getMessage()); return; } if (empty($atok)) { common_debug('couldn\'t get access token.'); print "Token exchange failed. Has the request token been authorized?\n"; } else { print $atok; } }
function api_oauth_access_token(&$a, $type) { try { $oauth = new FKOAuth1(); $req = OAuthRequest::from_request(); $r = $oauth->fetch_access_token($req); } catch (Exception $e) { echo "error=" . OAuthUtil::urlencode_rfc3986($e->getMessage()); killme(); } echo $r; killme(); }