function authenticate() { $db = $this->db; $provider = new OAuthProvider(); $provider->is2LeggedEndpoint(TRUE); $provider->consumerHandler(function ($provider) use($db) { $stmt = $db->prepare('SELECT consumerSecret FROM storageConsumers WHERE consumerKey = :key'); $stmt->bindParam(':key', $provider->consumer_key); $stmt->execute(); $row = $stmt->fetch(); if ($row === FALSE || empty($row)) { return OAUTH_CONSUMER_KEY_UNKNOWN; } $provider->consumer_secret = $row['consumerSecret']; return OAUTH_OK; }); $provider->timestampNonceHandler(function ($provider) { if ($provider->nonce == "bad") { return OAUTH_BAD_NONCE; } else { if ($provider->timestamp == "0") { return OAUTH_BAD_TIMESTAMP; } } return OAUTH_OK; }); $provider->checkOAuthRequest(); $this->consumerKey = $provider->consumer_key; }
public function oauth() { if (!$this->oauth) { $this->oauth = OAuthProvider::factory($this->OAuthProviderClass, $this->initArgs); } return $this->oauth; }
public function getOAuthProvider() { if (!$this->OAuthProvider) { $this->OAuthProvider = OAuthProvider::factory($this->OAuthProviderClass, $this->initArgs); } return $this->OAuthProvider; }
protected function init($args) { parent::init($args); if (!isset($args['OAUTH_CONSUMER_KEY'], $args['OAUTH_CONSUMER_SECRET']) || strlen($args['OAUTH_CONSUMER_KEY']) == 0 || strlen($args['OAUTH_CONSUMER_SECRET']) == 0) { throw new KurogoConfigurationException("Twitter Consumer key and secret not set"); } }
public function generateaccesstoken() { if ($this->oauth_error) { return FALSE; } $access_token = md5(OAuthProvider::generateToken(20, FALSE)); $access_token_secret = md5(OAuthProvider::generateToken(20, FALSE)); $token = token::findbytoken($this->oauth->token); if (is_object($token)) { $token->changetoaccesstoken($access_token, $access_token_secret); return "access_token=" . $token->gettoken() . "&access_token_secret=" . $token->gettokensecret(); } $this->oauth_error = TRUE; return FALSE; }
public function onRoute(MvcEvent $mvcEvent) { $request = $mvcEvent->getRequest(); $response = $mvcEvent->getResponse(); $app = $mvcEvent->getApplication(); $match = $app->getMvcEvent()->getRouteMatch(); $routeName = $match->getMatchedRouteName(); $method = strtolower($request->getMethod()); if (!$this->acl->hasResource($routeName)) { return; } $role = null; /** * Infer that if : * 1. the request is protected under 2 legged oauth, * then it is a 2 legged oauth request * 2. the request is protected under 3 legged oauth, * then it is a 3 legged oauth request * 3. otherwise it is not protected */ if ($this->acl->isAllowed(BgOauthProviderAcl::TWO_LEGGED, $routeName, $method)) { $role = BgOauthProviderAcl::TWO_LEGGED; $this->oauthProvider->is2LeggedEndpoint(); } elseif ($this->acl->isAllowed(BgOauthProviderAcl::THREE_LEGGED, $routeName, $method)) { $role = BgOauthProviderAcl::THREE_LEGGED; } else { return; } try { $this->oauthProvider->checkOAuthRequest(); } catch (\OAuthException $e) { $error = \OAuthProvider::reportProblem($e); $response->setStatusCode(400); $response->setContent($error); $response->getHeaders()->addHeaders(array('WWW-Authenticate' => $error)); return $response; } //Unreachable (I think). if (!$this->acl->isAllowed($role, $routeName, $method)) { $responseBody = array(); $responseBody['error'] = 'Not Authorised'; $responseBody['request'] = $request->getRequestUri(); $response->setStatusCode(401); $response->setContent(json_encode($responseBody)); $response->setHeaders($response->getHeaders()->addHeaderLine('Content-Type', 'application/json')); return $response; } }
public function onRoute(MvcEvent $mvcEvent) { $request = $mvcEvent->getRequest(); $response = $mvcEvent->getResponse(); /** * If it's a CLI request - return. */ if ($request instanceof \Zend\Console\Request) { return; } $app = $mvcEvent->getApplication(); $match = $app->getMvcEvent()->getRouteMatch(); $routeName = $match->getMatchedRouteName(); $method = strtolower($request->getMethod()); if (!$this->acl->hasResource($routeName)) { return; } $role = null; /** * Infer that if : * 1. the request is protected under 2 legged oauth, * then it is a 2 legged oauth request * 2. the request is protected under 3 legged oauth, * then it is a 3 legged oauth request * 3. otherwise it is not protected */ if ($this->acl->isAllowed(BgOauthProviderAcl::TWO_LEGGED, $routeName, $method)) { $role = BgOauthProviderAcl::TWO_LEGGED; $this->oauthProvider->is2LeggedEndpoint(); } elseif ($this->acl->isAllowed(BgOauthProviderAcl::THREE_LEGGED, $routeName, $method)) { $role = BgOauthProviderAcl::THREE_LEGGED; } else { return; } try { $this->oauthProvider->checkOAuthRequest(); } catch (\OAuthException $e) { $error = \OAuthProvider::reportProblem($e, false); $response->setStatusCode(Response::STATUS_CODE_401); $response->setContent($error); $response->getHeaders()->addHeaders(array('WWW-Authenticate' => $error)); $mvcEvent->setError(self::ERROR); $mvcEvent->getApplication()->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $mvcEvent); return $response; } //Success! }
public function __construct($query_get) { $this->__action = $this->_get_action($query_get); try { $this->__provider = new OAuthProvider(); $this->__provider->consumerHandler(array($this, 'lookupConsumer')); $this->__provider->timestampNonceHandler(array($this, 'timestampNonceChecker')); $this->__provider->tokenHandler(array($this, 'tokenHandler')); $this->__provider->setParam('kohana_uri', NULL); // Ignore the kohana_uri parameter $this->__provider->setRequestTokenPath('/v1/oauth/request_token'); // No token needed for this end point $this->__provider->checkOAuthRequest(); } catch (OAuthException $E) { echo OAuthProvider::reportProblem($E); $this->oauth_error = true; } }
public function endpoint() { $provider = new MyOAuthProvider(); //we need to disable a check if it is our first call to requesttoken. $c = strtolower($this->args('api_call')); if ($c == 'requesttoken') { $provider->oauth->isRequestTokenEndpoint(true); $this->set('provider', $provider); } elseif ($c == 'accesstoken') { $this->set('provider', $provider); } try { $provider->oauth->checkOAuthRequest(); $calls = array('requesttoken', 'accesstoken', 'listqueues', 'queueinfo', 'createqueue', 'listjobs', 'jobinfo', 'grabjob', 'grabslicejob', 'findnewjob', 'dropjob', 'canceljob', 'completejob', 'completeslicejob', 'downloadedjob', 'createjob', 'updatejobprogress', 'listbots', 'botinfo', 'registerbot', 'updatebot', 'updateslicejob', 'webcamupdate', 'getmybots', 'devicescanresults'); if (in_array($c, $calls)) { $this->token = $provider->token; // TODO Find out if consumer is even needed $this->consumer = $provider->consumer; $fname = "api_{$c}"; $data = $this->{$fname}(); } else { throw new Exception("Specified api_call '{$c}' does not exist."); } $result = array('status' => 'success', 'data' => $data); } catch (OAuthException $e) { error_log("Something went wrong with OAuth"); error_log($e->getMessage()); error_log(print_r($this->args(), true)); error_log(print_r($provider->oauth, true)); error_log(OAuthProvider::reportProblem($e, true)); $result = array('status' => 'error', 'error' => $e->getMessage()); } catch (Exception $e) { error_log($e->getMessage()); error_log(print_r($this->args(), true)); $result = array('status' => 'error', 'error' => $e->getMessage()); } //add in our version. $result['_api_version'] = self::$api_version; echo JSON::encode($result); exit; }
protected function init($args) { parent::init($args); if (isset($args['GOOGLE_REQUIRE_LOGIN'])) { $this->requireLogin = $args['GOOGLE_REQUIRE_LOGIN']; } if (isset($args['OPENID_REALM'])) { if (!preg_match("@^https?://@", $args['OPENID_REALM'])) { throw new KurogoConfigurationException("Invalid OpenID realm {$args['OPENID_REALM']}. Realm must be a full url"); } $this->realm = $args['OPENID_REALM']; } if (isset($args['OAUTH_CONSUMER_KEY'], $args['OAUTH_CONSUMER_SECRET'])) { if (!isset($args['GOOGLE_SCOPE'])) { throw new KurogoConfigurationException("GOOGLE_SCOPE parameter must be specified"); } elseif (!is_array($args['GOOGLE_SCOPE'])) { throw new KurogoConfigurationException("GOOGLE_SCOPE parameter is not an array"); } $this->scope = $args['GOOGLE_SCOPE']; } }
public function setUpOAuthAndDb($db) { $this->db = $db; try { $this->provider = new OAuthProvider(); $this->provider->consumerHandler(array($this, 'lookupConsumer')); $this->provider->timestampNonceHandler(array($this, 'timestampNonceChecker')); $this->provider->tokenHandler(array($this, 'tokenHandler')); $this->provider->setRequestTokenPath('/v2/oauth/request_token'); // No token needed for this end point $this->provider->checkOAuthRequest(); } catch (OAuthException $E) { error_log(OAuthProvider::reportProblem($E)); return false; } return true; }
public static function generateToken() { return sha1(OAuthProvider::generateToken(20)); }
/** * This function generates a verifier and returns it */ public function generateVerifier() { $verifier = sha1(OAuthProvider::generateToken(20, true)); return $verifier; }
public function getErrorAsString() { return OAuthProvider::reportProblem($this->oauthException); }
<?php include 'common.inc.php'; try { $provider = new OAuthProvider($params); /* the endpoint which issues a request token is special, it doesn't take an oauth_token and hence there's no call to the tokenHandler() */ $provider->isRequestTokenEndpoint(true); /* OAuthProvider will call this callback with the $provider object as an argument, you can throw errors from that handler and set the $provider->consumer_key if all is good */ $provider->consumerHandler('lookupConsumer'); /* similar to consumerHandler, throw errors related to the timestamp/nonce in this callback */ $provider->timestampNonceHandler('timestampNonceChecker'); /* this is the meat of request authorization, the first argument is the URL of this endpoint as the outside world sees it * the optional second argument is the HTTP method, GET, POST, etc ... the provider will try to detect this via $_SERVER["REQUEST_METHOD"] (usually reliable) when it's not set */ $provider->checkOAuthRequest("http://localhost/request_token.php", PHP_SAPI == "cli" ? OAUTH_HTTP_METHOD_GET : NULL); } catch (OAuthException $E) { /* when you catch OAuthException and echo OAuthProvider::reportProblem with it, you'll get the problem reporting extension described here: * http://wiki.oauth.net/ProblemReporting for free, it also sets the most appropriate HTTP response code */ echo OAuthProvider::reportProblem($E); }
public function accessTokenAction() { $oauthProvider = $this->oauthProvider; $response = $this->getResponse(); try { $oauthProvider->checkOAuthRequest(); $accessToken = $oauthProvider->saveAccessToken(); $responseUrl = array(); $responseUrl['oauth_token'] = $accessToken->getToken(); $responseUrl['oauth_token_secret'] = $accessToken->getTokenSecret(); $response->setContent(http_build_query($responseUrl)); } catch (\OAuthException $e) { $error = \OAuthProvider::reportProblem($e); $response->setStatusCode(400); $response->setContent($error); $response->getHeaders()->addHeaders(array('WWW-Authenticate' => $error)); } return $response; }
/** * OAuthServer constructor. At this stage does not do anything. */ public function __construct($db) { parent::__construct(); $this->db = $db; }
/** * Wrapper around OAuthProvider::generateToken to add sha1 hashing at one place * @static * @param bool $sha1 * @return string */ public static function generateToken() { $token = OAuthProvider::generateToken(40, true); return sha1($token); }
<?php include 'common.inc.php'; try { $provider = new OAuthProvider($params); $provider->your_own_member = "this is passed to every callback"; $provider->consumerHandler('lookupConsumer'); $provider->timestampNonceHandler('timestampNonceChecker'); $provider->tokenHandler('tokenHandler'); $provider->checkOAuthRequest("http://localhost/a_private_api.php", PHP_SAPI == "cli" ? OAUTH_HTTP_METHOD_GET : NULL); } catch (OAuthException $E) { echo OAuthProvider::reportProblem($E); }
/** * Short description for 'access_token' * * Long description (if any) ... * * @return unknown Return description (if any) ... */ private function access_token() { if (empty($this->_provider)) { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=bad oauth provider', 501, 'Internal Server Error'); return; } JLoader::import('Hubzero.User.Password'); $xauth_request = false; $header = ''; if (isset($_SERVER['HTTP_AUTHORIZATION'])) { $header = $_SERVER['HTTP_AUTHORIZATION']; } // @FIXME: header check is inexact and could give false positives // @FIXME: pecl oauth provider doesn't handle x_auth in header // @FIXME: api application should convert xauth variables in // header to form/query data as workaround // @FIXME: this code is here for future use if/when pecl oauth // provider is fixed // if (isset($_GET['x_auth_mode']) || isset($_GET['x_auth_username']) || isset($_GET['x_auth_password']) || isset($_POST['x_auth_mode']) || isset($_POST['x_auth_username']) || isset($_POST['x_auth_password']) || strpos($header, 'x_auth_mode') !== false || strpos($header, 'x_auth_username') !== false || strpos($header, 'x_auth_mode') !== false) { $xauth_request = true; } if ($xauth_request) { if ($this->_provider->getConsumerData()->xauth == '0') { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=permission_denied', 401, 'Unauthorized0'); return; } if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off') { $this->_response->setErrorMessage('SSL Required', 403, 'Forbidden'); return; } if (isset($this->_provider->x_auth_mode)) { $x_auth_mode = $this->_provider->x_auth_mode; } else { if (isset($_POST['x_auth_mode'])) { $x_auth_mode = $_POST['x_auth_mode']; } else { if (isset($_GET['x_auth_mode'])) { $x_auth_mode = $_GET['x_auth_mode']; } else { $x_auth_mode = ''; } } } if (isset($this->_provider->x_auth_username)) { $x_auth_username = $this->_provider->x_auth_username; } else { if (isset($_POST['x_auth_username'])) { $x_auth_username = $_POST['x_auth_username']; } else { if (isset($_GET['x_auth_username'])) { $x_auth_username = $_GET['x_auth_username']; } else { $x_auth_username = ''; } } } if (isset($this->_provider->x_auth_password)) { $x_auth_password = $this->_provider->x_auth_password; } else { if (isset($_POST['x_auth_password'])) { $x_auth_password = $_POST['x_auth_password']; } else { if (isset($_GET['x_auth_password'])) { $x_auth_password = $_GET['x_auth_password']; } else { $x_auth_password = ''; } } } if ($x_auth_mode != 'client_auth') { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=permission_denied', 400, 'Bad Request'); return; } $match = \Hubzero\User\Password::passwordMatches($x_auth_username, $x_auth_password, true); if (!$match) { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setErrorMessage('oauth_problem=permission_denied', 401, 'Unauthorized'); return; } $useraccount = User::getInstance(JUserHelper::getUserId($x_auth_username)); $db = App::get('db'); $db->setQuery("SELECT token,token_secret FROM #__oauthp_tokens WHERE consumer_id=" . $db->Quote($this->_provider->getConsumerData()->id) . " AND user_id =" . $db->Quote($useraccount->get('id')) . " LIMIT 1;"); $result = $db->loadObject(); if ($result === false) { $this->_response->setErrorMessage(500, 'Internal Server Error'); return; } if (!is_object($result)) { if ($this->_provider->getConsumerData()->xauth_grant < 1) { $this->_response->setErrorMessage(501, 'Internal Server Error'); return; } $token = sha1(OAuthProvider::generateToken(20, false)); $token_secret = sha1(OAuthProvider::generateToken(20, false)); $db = App::get('db'); $db->setQuery("INSERT INTO #__oauthp_tokens (consumer_id,user_id,state,token,token_secret,callback_url) VALUE (" . $db->Quote($this->_provider->getConsumerData()->id) . "," . $db->Quote($useraccount->get('id')) . "," . "'1'," . $db->Quote($token) . "," . $db->Quote($token_secret) . "," . $db->Quote($this->_provider->getConsumerData()->callback_url) . ");"); if (!$db->query()) { $this->_response->setErrorMessage(502, 'Internal Server Error'); return; } if ($db->getAffectedRows() < 1) { $this->_response->setErrorMessage(503, 'Internal Server Error'); return; } $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setMessage("oauth_token=" . $token . "&oauth_token_secret=" . $token_secret, 200, "OK"); } else { $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setMessage("oauth_token=" . $result->token . "&oauth_token_secret=" . $result->token_secret, 200, "OK"); } return; } else { $this->_response->setErrorMessage(503, 'Internal Server Error'); return; // @FIXME: we don't support 3-legged auth yet // lookup request token to access token, give out access token // check verifier // check used flag $this->_response->setResponseProvides('application/x-www-form-urlencoded,text/html;q=0.9'); $this->_response->setMessage("oauth_token=" . $token . "&oauth_token_secret=" . $token_secret, 200, "OK"); return; } }
/** * Retrieves a token for use in registering this Known site with a hub. Tokens last for 10 minutes. * @return string */ function getRegistrationToken() { if (empty(site()->config->hub_settings)) { site()->config->hub_settings = []; } if (!empty(site()->config->hub_settings['registration_token'])) { if (!empty(site()->config->hub_settings['registration_token_expiry'])) { if (site()->config->hub_settings['registration_token_expiry'] > time() - 600) { return site()->config->hub_settings['registration_token']; } } } $token_generator = new \OAuthProvider([]); $token = $token_generator->generateToken(32); $config = site()->config; $config->hub_settings['registration_token'] = bin2hex($token); $config->hub_settings['registration_token_expiry'] = time(); $config->save(); site()->config = $config; return site()->config->hub_settings['registration_token']; }
public function flow() { if (isset($_GET['oauth_token'])) { $consumerKey = $_GET['oauth_consumer_key']; $consumerSecret = $_GET['oauth_consumer_secret']; $token = $_GET['oauth_token']; $tokenSecret = $_GET['oauth_token_secret']; $verifier = $_GET['oauth_verifier']; try { $consumer = getDb()->getCredential($token); $oauth = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $oauth->setVersion('1.0a'); $oauth->setToken($token, $tokenSecret); $accessToken = $oauth->getAccessToken(sprintf('%s://%s/v1/oauth/token/access', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST']), null, $verifier); $accessToken['oauth_consumer_key'] = $consumerKey; $accessToken['oauth_consumer_secret'] = $consumerSecret; setcookie('oauth', http_build_query($accessToken)); if (!isset($accessToken['oauth_token']) || !isset($accessToken['oauth_token_secret'])) { echo sprintf('Invalid response when getting an access token: %s', http_build_query($accessToken)); } else { echo sprintf('You exchanged a request token for an access token<br><a href="?reloaded=1">Reload to make an OAuth request</a>', $accessToken['oauth_token'], $accessToken['oauth_token_secret']); } } catch (OAuthException $e) { $message = OAuthProvider::reportProblem($e); getLogger()->info($message); OPException::raise(new OPAuthorizationOAuthException($message)); } } else { if (!isset($_GET['reloaded'])) { $callback = sprintf('%s://%s/v1/oauth/flow', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST']); $name = isset($_GET['name']) ? $_GET['name'] : 'OAuth Test Flow'; echo sprintf('<a href="%s://%s/v1/oauth/authorize?oauth_callback=%s&name=%s">Create a new client id</a>', $this->utility->getProtocol(false), $_SERVER['HTTP_HOST'], urlencode($callback), urlencode($name)); } else { try { parse_str($_COOKIE['oauth']); $consumer = getDb()->getCredential($oauth_token); $oauth = new OAuth($oauth_consumer_key, $oauth_consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION); $oauth->setToken($oauth_token, $oauth_token_secret); $oauth->fetch(sprintf('http://%s/v1/oauth/test?oauth_consumer_key=%s', $_SERVER['HTTP_HOST'], $oauth_consumer_key)); $response_info = $oauth->getLastResponseInfo(); header("Content-Type: {$response_info["content_type"]}"); echo $oauth->getLastResponse(); } catch (OAuthException $e) { $message = OAuthProvider::reportProblem($e); getLogger()->info($message); OPException::raise(new OPAuthorizationOAuthException($message)); } } } }
/** * Attempt to validate the incoming LTI request. */ public function __construct() { try { $this->oauthProvider = new OAuthProvider(); $this->oauthProvider->consumerHandler(array($this, 'consumerHandler')); $this->oauthProvider->timestampNonceHandler(array($this, 'timestampNonceHandler')); $this->oauthProvider->isRequestTokenEndpoint(true); $this->oauthProvider->setParam('url', NULL); $this->oauthProvider->checkOAuthRequest(); } catch (OAuthException $e) { LTI::log(OAuthProvider::reportProblem($e)); switch ($e->getCode()) { case OAUTH_BAD_NONCE: wp_die(__('This LTI request has expired. Please return to your application and restart the launch process.'), __('LTI Error')); break; case OAUTH_BAD_TIMESTAMP: wp_die(__('This request is too old. Please return to your application and restart the launch process.'), __('LTI Error')); break; case OAUTH_CONSUMER_KEY_UNKNOWN: wp_die(__('Consumer key is unknown, or has been temporarily disabled. Please check your consumer key settings and restart the launch process.'), __('LTI Error')); break; case OAUTH_CONSUMER_KEY_REFUSED: wp_die(__('The consumer key was refused. Please check your configuration and follow up with the LTI provider for support.'), __('LTI Error')); break; case OAUTH_INVALID_SIGNATURE: wp_die(__('The request signature is invalid, or does not match the signature computed.'), __('LTI Error')); break; case OAUTH_PARAMETER_ABSENT: wp_die(__('A required launch parameter was not provided.'), __('LTI Error')); break; case OAUTH_SIGNATURE_METHOD_REJECTED: wp_die(__('The signature method was not accepted by the service provider.'), __('LTI Error')); break; default: // We really shouldn't get any of the other OAuthProvider error codes. // log this. wp_die(__('General launch error. Please follow up with the tool provider to consult any logs to further diagnose the issue.'), __('LTI Error')); break; } } }