Beispiel #1
0
 /**
  * Validate signature based on the signature method used.
  *
  * @param array $params
  * @param string $consumerSecret
  * @param string $httpMethod
  * @param string $requestUrl
  * @param string $tokenSecret
  * @return void
  * @throws Exception|OauthInputException
  */
 protected function _validateSignature($params, $consumerSecret, $httpMethod, $requestUrl, $tokenSecret = null)
 {
     if (!in_array($params['oauth_signature_method'], self::getSupportedSignatureMethods())) {
         throw new OauthInputException('Signature method %1 is not supported', [$params['oauth_signature_method']]);
     }
     $allowedSignParams = $params;
     unset($allowedSignParams['oauth_signature']);
     $calculatedSign = $this->_httpUtility->sign($allowedSignParams, $params['oauth_signature_method'], $consumerSecret, $tokenSecret, $httpMethod, $requestUrl);
     if ($calculatedSign != $params['oauth_signature']) {
         throw new Exception('Invalid signature');
     }
 }
Beispiel #2
0
 public function testBuildAuthorizationHeader()
 {
     $signature = 'valid_signature';
     $this->_httpUtilityMock->expects($this->any())->method('sign')->will($this->returnValue($signature));
     $this->_setupConsumer(false);
     $this->_oauthHelperMock->expects($this->any())->method('generateRandomString')->will($this->returnValue('tyukmnjhgfdcvxstyuioplkmnhtfvert'));
     $request = ['oauth_consumer_key' => 'edf957ef88492f0a32eb7e1731e85da2', 'oauth_consumer_secret' => 'asdawwewefrtyh2f0a32eb7e1731e85d', 'oauth_token' => '7c0709f789e1f38a17aa4b9a28e1b06c', 'oauth_token_secret' => 'a6agsfrsfgsrjjjjyy487939244ssggg', 'custom_param1' => 'foo', 'custom_param2' => 'bar'];
     $requestUrl = 'http://www.example.com/endpoint';
     $oauthHeader = $this->_oauth->buildAuthorizationHeader($request, $requestUrl);
     $expectedHeader = 'OAuth oauth_nonce="tyukmnjhgfdcvxstyuioplkmnhtfvert",' . 'oauth_timestamp="",' . 'oauth_version="1.0",oauth_consumer_key="edf957ef88492f0a32eb7e1731e85da2",' . 'oauth_consumer_secret="asdawwewefrtyh2f0a32eb7e1731e85d",' . 'oauth_token="7c0709f789e1f38a17aa4b9a28e1b06c",' . 'oauth_token_secret="a6agsfrsfgsrjjjjyy487939244ssggg",' . 'oauth_signature="valid_signature"';
     $this->assertEquals($expectedHeader, $oauthHeader, 'Generated Oauth header is incorrect');
 }
Beispiel #3
0
 /**
  * Test two legged authentication
  */
 public function testAuthenticateTwoLegged()
 {
     $testUserKey = 'foo_user';
     $testUserSecret = 'bar_secret';
     $testUrl = 'http://foo.bar/api/rest/v1/baz';
     // Prepare signature and oAuth parameters
     $utility = new Zend_Oauth_Http_Utility();
     $params = array('oauth_consumer_key' => $testUserKey, 'oauth_nonce' => $utility->generateNonce(), 'oauth_timestamp' => $utility->generateTimestamp(), 'oauth_version' => '1.0', 'oauth_signature_method' => Mage_Oauth_Model_Server::SIGNATURE_PLAIN);
     $params['oauth_signature'] = $utility->sign($params, Mage_Oauth_Model_Server::SIGNATURE_PLAIN, $testUserSecret, '', 'GET', $testUrl);
     $authHeader = $utility->toAuthorizationHeader($params);
     $this->_requestMock->expects($this->at(0))->method('getHeader')->with('Authorization')->will($this->returnValue($authHeader));
     $this->_requestMock->expects($this->at(1))->method('getHeader')->with(Zend_Http_Client::CONTENT_TYPE)->will($this->returnValue('application/json'));
     $this->_requestMock->expects($this->any())->method('getScheme')->with()->will($this->returnValue(Zend_Controller_Request_Http::SCHEME_HTTP));
     $this->_requestMock->expects($this->any())->method('getHttpHost')->with()->will($this->returnValue('foo.bar'));
     $this->_requestMock->expects($this->any())->method('getRequestUri')->with()->will($this->returnValue('/api/rest/v1/baz'));
     $userMock = $this->getMockBuilder('Mage_Webapi_Model_Acl_User')->setMethods(array('loadByKey', 'getId', 'getSecret'))->disableOriginalConstructor()->getMock();
     $this->_consumerFactoryMock->expects($this->once())->method('create')->will($this->returnValue($userMock));
     $userMock->expects($this->once())->method('loadByKey')->with($testUserKey)->will($this->returnSelf());
     $userMock->expects($this->once())->method('getId')->with()->will($this->returnValue(1));
     $userMock->expects($this->once())->method('getSecret')->with()->will($this->returnValue($testUserSecret));
     $this->assertEquals($userMock, $this->_server->authenticateTwoLegged());
 }
 /**
  * Get base signature string
  *
  * @param  array $params
  * @param  null|string $method
  * @param  null|string $url
  * @return string
  */
 protected function _getBaseSignatureString(array $params, $method = null, $url = null)
 {
     $encodedParams = array();
     foreach ($params as $key => $value) {
         $encodedParams[Zend_Oauth_Http_Utility::urlEncode($key)] = Zend_Oauth_Http_Utility::urlEncode($value);
     }
     $baseStrings = array();
     if (isset($method)) {
         $baseStrings[] = strtoupper($method);
     }
     if (isset($url)) {
         // should normalise later
         $baseStrings[] = Zend_Oauth_Http_Utility::urlEncode($this->normaliseBaseSignatureUrl($url));
     }
     if (isset($encodedParams['oauth_signature'])) {
         unset($encodedParams['oauth_signature']);
     }
     $baseStrings[] = Zend_Oauth_Http_Utility::urlEncode($this->_toByteValueOrderedQueryString($encodedParams));
     return implode('&', $baseStrings);
 }
Beispiel #5
0
 public function testUrlEncodeCorrectlyEncodesU3001()
 {
     $string = '、';
     $this->assertEquals('%E3%80%81', Zend_Oauth_Http_Utility::urlEncode($string));
 }
Beispiel #6
0
 /**
  * Generates a valid OAuth Authorization header based on the provided
  * parameters and realm.
  *
  * @param  array $params
  * @param  string $realm
  * @return string
  */
 protected function _toAuthorizationHeader(array $params, $realm = null)
 {
     $headerValue = array();
     $headerValue[] = 'OAuth realm="' . $realm . '"';
     foreach ($params as $key => $value) {
         if (!preg_match("/^oauth_/", $key)) {
             continue;
         }
         $headerValue[] = Zend_Oauth_Http_Utility::urlEncode($key) . '="' . Zend_Oauth_Http_Utility::urlEncode($value) . '"';
     }
     return implode(",", $headerValue);
 }
Beispiel #7
0
 /**
  * Validate signature
  *
  * @throws Mage_Oauth_Exception
  */
 protected function _validateSignature()
 {
     $util = new Zend_Oauth_Http_Utility();
     $calculatedSign = $util->sign(array_merge($this->_params, $this->_protocolParams), $this->_protocolParams['oauth_signature_method'], $this->_consumer->getSecret(), $this->_token->getSecret(), $this->_request->getMethod(), $this->_request->getScheme() . '://' . $this->_request->getHttpHost() . $this->_request->getRequestUri());
     if ($calculatedSign != $this->_protocolParams['oauth_signature']) {
         $this->_throwException('', self::ERR_SIGNATURE_INVALID);
     }
 }
Beispiel #8
0
 /**
  * Convert Token to a string, specifically a raw encoded query string.
  *
  * @return string
  */
 public function toString()
 {
     return $this->_httpUtility->toEncodedQueryString($this->_params);
 }
Beispiel #9
0
 /**
  * Get OAuth 'Authentication' header string
  *
  * @return string
  */
 public function getOauthHeader()
 {
     $this->_oauthParams['oauth_timestamp'] = time();
     $this->_oauthParams['oauth_nonce'] = md5(uniqid(rand(), true));
     // http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/drafts/5/spec.html
     // Haven't fully implemented that spec, but the idea is the same.
     // TODO: The server should validate this hash to be more secure
     $this->_oauthParams['oauth_body_hash'] = $this->_getRequestHash();
     $this->_generateOauthSignature('POST');
     $headerValue = array();
     foreach ($this->_oauthParams as $key => $value) {
         $headerValue[] = Zend_Oauth_Http_Utility::urlEncode($key) . '="' . Zend_Oauth_Http_Utility::urlEncode($value) . '"';
     }
     return implode(",", $headerValue);
 }
 /**
  * Validate OAuth request
  * @param Zend_Uri_Http $url Request URL, will use current if null
  * @param array $params Additional parameters
  * @return bool
  * @throws Zend_Oauth_Exception
  */
 public function checkOAuthRequest(Zend_Uri_Http $url = null, $params = array())
 {
     if (empty($url)) {
         $this->url = $this->getRequestUrl();
     } else {
         $this->url = clone $url;
     }
     // We'll ignore query for the pruposes of URL matching
     $this->url->setQuery('');
     if (isset($_SERVER['REQUEST_METHOD'])) {
         $method = $_SERVER['REQUEST_METHOD'];
     } elseif (isset($_SERVER['HTTP_METHOD'])) {
         $method = $_SERVER['HTTP_METHOD'];
     } else {
         $method = 'GET';
     }
     $params = $this->assembleParams($method, $params);
     $this->checkSignatureMethod($params['oauth_signature_method']);
     $this->checkRequiredParams($params);
     $this->timestamp = $params['oauth_timestamp'];
     $this->nonce = $params['oauth_nonce'];
     $this->consumer_key = $params['oauth_consumer_key'];
     if (!is_callable($this->nonceHandler)) {
         throw new Zend_Oauth_Exception("Nonce handler not callable", self::BAD_NONCE);
     }
     $res = call_user_func($this->nonceHandler, $this);
     if ($res != self::OK) {
         throw new Zend_Oauth_Exception("Invalid request", $res);
     }
     if (!is_callable($this->consumerHandler)) {
         throw new Zend_Oauth_Exception("Consumer handler not callable", self::CONSUMER_KEY_UNKNOWN);
     }
     $res = call_user_func($this->consumerHandler, $this);
     // this will set $this->consumer_secret if OK
     if ($res != self::OK) {
         throw new Zend_Oauth_Exception("Consumer key invalid", $res);
     }
     if ($this->needsToken()) {
         $this->token = $params['oauth_token'];
         $this->verifier = $params['oauth_verifier'];
         if (!is_callable($this->tokenHandler)) {
             throw new Zend_Oauth_Exception("Token handler not callable", self::TOKEN_REJECTED);
         }
         $res = call_user_func($this->tokenHandler, $this);
         // this will set $this->token_secret if OK
         if ($res != self::OK) {
             throw new Zend_Oauth_Exception("Token invalid", $res);
         }
     }
     $util = new Zend_Oauth_Http_Utility();
     $req_sign = $params['oauth_signature'];
     unset($params['oauth_signature']);
     $our_sign = $util->sign($params, $params['oauth_signature_method'], $this->consumer_secret, $this->token_secret, $method, $this->url->getUri());
     if ($req_sign != $our_sign) {
         // TODO: think how to extract signature base string
         $this->problem = $our_sign;
         throw new Zend_Oauth_Exception("Invalid signature", self::INVALID_SIGNATURE);
     }
     return true;
 }
require_once 'Zend/Oauth.php';
require_once 'Zend/Oauth/Config.php';
require_once 'Zend/Oauth/Token/Access.php';
require_once 'Zend/Mail/Protocol/Imap.php';
require_once 'Zend/Mail/Storage/Imap.php';
/**
 * Setup OAuth
 */
$options = array('requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER, 'version' => '1.0', 'signatureMethod' => 'HMAC-SHA1', 'consumerKey' => $TWO_LEGGED_CONSUMER_KEY, 'consumerSecret' => $TWO_LEGGED_CONSUMER_SECRET_HMAC);
$config = new Zend_Oauth_Config();
$config->setOptions($options);
$config->setToken(new Zend_Oauth_Token_Access());
$config->setRequestMethod('GET');
$url = 'https://mail.google.com/mail/b/' . $TWO_LEGGED_EMAIL_ADDRESS . '/imap/';
$urlWithXoauth = $url . '?xoauth_requestor_id=' . urlencode($TWO_LEGGED_EMAIL_ADDRESS);
$httpUtility = new Zend_Oauth_Http_Utility();
/**
 * Get an unsorted array of oauth params,
 * including the signature based off those params.
 */
$params = $httpUtility->assembleParams($url, $config, array('xoauth_requestor_id' => $TWO_LEGGED_EMAIL_ADDRESS));
/**
 * Sort parameters based on their names, as required
 * by OAuth.
 */
ksort($params);
/**
 * Construct a comma-deliminated,ordered,quoted list of 
 * OAuth params as required by XOAUTH.
 * 
 * Example: oauth_param1="foo",oauth_param2="bar"
Beispiel #12
0
 /**
  * Send a request
  * @param String $method Methodname
  * @param Array $queryParams GET parameters
  * @return Array
  */
 public function request($method, array $queryParams)
 {
     $queryParams['format'] = self::RESPONSE_FORMAT;
     if (!substr($method, 0, 5) != 'vimeo') {
         $method = 'vimeo.' . $method;
     }
     $queryParams['method'] = $method;
     $queryString = http_build_query($queryParams);
     $url = self::VIMEO_API_URL . '?' . $queryString;
     $oAuthHttpUtility = new Zend_Oauth_Http_Utility();
     $params = array('oauth_consumer_key' => $this->getConsumerKey(), 'oauth_nonce' => $oAuthHttpUtility->generateNonce(), 'oauth_timestamp' => $oAuthHttpUtility->generateTimestamp(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_version' => '1.0');
     if ($this->getAccessToken()) {
         $params['oauth_token'] = $this->getAccessToken();
     }
     $params['oauth_signature'] = $oAuthHttpUtility->sign(array_merge($queryParams, $params), 'HMAC-SHA1', $this->getConsumerSecret(), $this->getAccessTokenSecret(), Zend_Oauth::GET, self::VIMEO_API_URL);
     $httpClient = $this->getHttpClient()->setHeaders('Authorization', $oAuthHttpUtility->toAuthorizationHeader($params))->setMethod(Zend_Http_Client::GET)->setUri($url);
     $response = $httpClient->request()->getBody();
     $response = json_decode($response, true);
     if ($response['stat'] == 'fail') {
         $error = 'An unknown error occurred at Vimeo.';
         if (!empty($response['err']['expl'])) {
             $error = $response['err']['expl'];
         }
         throw new Garp_Service_Vimeo_Exception($response['err']['expl']);
     }
     return $response;
 }
        $consumer->redirect();
    } else {
        // Have Request Token already, Get Access Token
        $_SESSION['ACCESS_TOKEN'] = serialize($consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN'])));
        header('Location: ' . getCurrentUrl(false));
        exit;
    }
} else {
    // Retrieve mail using Access Token
    $accessToken = unserialize($_SESSION['ACCESS_TOKEN']);
    $config = new Zend_Oauth_Config();
    $config->setOptions($options);
    $config->setToken($accessToken);
    $config->setRequestMethod('GET');
    $url = 'https://mail.google.com/mail/b/' . $email_address . '/imap/';
    $httpUtility = new Zend_Oauth_Http_Utility();
    /**
     * Get an unsorted array of oauth params,
     * including the signature based off those params.
     */
    $params = $httpUtility->assembleParams($url, $config);
    /**
     * Sort parameters based on their names, as required
     * by OAuth.
     */
    ksort($params);
    /**
     * Construct a comma-deliminated,ordered,quoted list of 
     * OAuth params as required by XOAUTH.
     * 
     * Example: oauth_param1="foo",oauth_param2="bar"