OAuth in simple php without class - php

i want to generate the signature this code gives me using simple php with no oauth class:
$oauth = new OAuth($my_key, $my_secret);
$bodyHash = base64_encode(sha1($body_content, true)); //contains the body
$sig = $oauth->generateSignature('GET', $url, Array("oauth_body_hash" => $bodyHash));
what i have done so far is this:
$bodyHash = base64_encode(sha1($xml, true));
$result_data = array(
'oauth_body_hash' => $bodyHash
);
$result_data_keys = array_keys($result_data);
sort($result_data_keys);
$launch_params = array();
foreach ($result_data_keys as $key) {
array_push($launch_params, $key . "=" . rawurlencode($result_data[$key]));
}
$base_string = "POST&" . urlencode($sUrl) . "&" . rawurlencode(implode("&", $launch_params));
$signature = base64_encode(hash_hmac("sha1", $base_string, $my_secret, true));
but im not getting the same signature!
this is the simplified version of the problem i have posted earlier here: Building a body signed oauth xml request for LTI Outcomes service
any idea what im doing wrong?

Related

Oauth signature generator failure

I am using php cURL to PUT some informations (Authorization type: Oauth 1.0),
my problem is about generate the unique signature using the consumer_secret and access_token and encoded URL and the '&' also,
I tried to use two methods to generate it but the cURL response is: The signature is invalid. Verify and try again.
this is my last method to generate the signature:
// ------------- START GENERATE SIGNATURE -------------
$oauth = array(
"OAuth oauth_consumer_key=".$this->consumer_key.",
oauth_token=".$this->access_token.",
oauth_signature_method=".$this->signature_method.",
oauth_timestamp=".$timestimp.",
oauth_nonce=".$nonce.",
oauth_version=".$this->version.""
);
$base_info = $this->buildBaseString($this->url, 'PUT', $oauth) .'&';
$composite_key = rawurlencode($this->consumer_secret) . '&' . rawurlencode($this->access_token);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
// ------------- END GENERATE SIGNATURE -------------
and this is the buildBaseString function
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
I need help please.
thanks.

Sinch voice callback request signin

I'm making app-to-phone app using Sinch.
I'm successfully providing the callback for ICE and ACE event without request signin.
But now, when I try to sign the request to make it more secure, it always fails to meet the requirement
I get my code from here : Trouble with authorization request
It works when I try to use data and application key from https://www.sinch.com/using-rest/#callbackrequestsigning
But when I try to use real data, it always fail.
$key = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxx";
$secret = 'my-app-secret';
$body = $request->getContent();
$timestamp = $request->input('timestamp');
$path = '/sinch/callback/' . $callbackType;
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:" . $timestamp;
$content_md5 = base64_encode( md5( utf8_encode($body), true ));
$string_to_sign =
"POST\n".
$content_md5."\n".
$content_type."\n".
$canonicalized_headers."\n".
$path;
$signature = base64_encode(hash_hmac("sha256", utf8_encode($string_to_sign), base64_decode($secret), true));
$authorizationHeader = $request->header('Authorization');
$sinchAuthorizationHeader = str_replace('Application ', '', $authorizationHeader);
$sinchAuthorizationHeader = explode(':', $sinchAuthorizationHeader);
if($sinchAuthorizationHeader[0] == $key && $signature == $sinchAuthorizationHeader[1]) {
return true;
}
return false;
Any help would be appreciated.

Google Tracks API "Bad Request" using PHP

I am using Google Tracks API to build a simple web based program to track a vehicle that has a tracking device sending latitude and longitude coordinates.
I am using PHP and the OAuth2 PHP library to make an authorized connection.
After authorizing and getting an access token I am making a request to create entities. Though I can't seem to get this working and keep getting a "400 Bad Request" response. Following all the steps shown in the documentation.
Here is my code:
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$parsedAuth['access_token'];
$data = array('entities' => array( "name"=> "Chevrolet" ));
$json_data = json_encode($data);
$data_length = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n". "Content-Length: " . strlen($data_length) . "\r\n",
'method' => 'POST',
'content' => $json_data
),
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
var_dump($response);
Exact Error is: "failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request"
Why am I getting a bad request? What would be a good request that will register these entities and return id's?
Thank you
The answer given here is wrong. The documentation states that it must be a POST see here My issue was not with the Auth but with the Tracks API itself. I ended up moving to create the request with CURL and it works just fine.
Please. This is PHP with CURL. It works 100%.
//Google maps tracks connection
//Get Files From PHP Library
require_once 'google-api-php-client/src/Google/autoload.php';
require_once 'google-api-php-client/src/Google/Service/MapsEngine.php';
//Set Client Credentials
$client_id = '*************.apps.googleusercontent.com'; //Client ID
$service_account_name = '************#developer.gserviceaccount.com'; //Email Address
$client_email = '*************#developer.gserviceaccount.com';
$private_key = file_get_contents('************.p12');
$scopes = array('https://www.googleapis.com/auth/tracks');
//Create Client
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//Send Credentials
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$client->setAssertionCredentials($credentials);
$_SESSION['service_token'] = $client->getAccessToken();
foreach ($_SESSION as $key=> $value) {
$vars = json_decode($value);
}
$parsedAuth = (array) $vars;
$token = $parsedAuth['access_token'];
//all functions in the program use this auth token- It should be global for easy accesses.
global $token;
function createEntities(){
global $token;
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$token;
//FIX ME: fields is temporarily hard coded- should be brought from DB
$fields = array(
'entities' => array(
'name' => "DemoTruck",
'type' => "AUTOMOBILE"
),
);
//json string the data for the POST
$query_string = '';
foreach($fields as $key => $array) {
$query_string .= '{"' . urlencode($key).'":[{';
foreach($array as $k => $v) {
$query_string .= '"' . urlencode($k) . '":"' . urlencode($v) . '",';
}
}
$str = rtrim($query_string , ',');
$fstr = $str.'}]}';
$length = strlen( $fstr );
//open connection
$ch = curl_init();
//test connection
if (FALSE === $ch)
throw new Exception('failed to initialize');
//set options
$header = array('Content-type: application/json');
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fstr);
$result = curl_exec($ch);
//dump in case of error
if (FALSE === $result){
var_dump( curl_error($ch) );
var_dump( curl_getinfo($ch) );
}
//close connection
curl_close($ch);
}

The request signature we calculated does not match the signature you provided. - Error in AWS

I have following code :
$method = "GET";
$host = "payments-sandbox.amazon.com";
$uri = "/cba/api/purchasecontract/";
$private_key='PRIVATE_KEY';
$time = date('c');
$params = array(
'AWSAccessKeyId' => $private_key,
'Action' => "CreatePurchaseContract",
'SignatureMethod' => "HmacSHA256",
'SignatureVersion' => "2",
'Timestamp' => $time);
uksort($params, 'strcmp');
$canonicalized_query = array();
foreach ($params as $param => $value) {
$param = str_replace("%7E", "~", rawurlencode($param));
$value = str_replace("%7E", "~", rawurlencode($value));
$canonicalized_query[] = $param . "=" . $value;
}
$canonicalized_query = implode("&", $canonicalized_query);
$string_to_sign = $method . "\n" . $host . "\n" . $uri . "\n" . $canonicalized_query;
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, $private_key, True));
$signature = str_replace("%7E", "~", rawurlencode($signature));
echo $url = "https://payments-sandbox.amazon.com/cba/api/purchasecontract/"
. "?Action=CreatePurchaseContract"
. "&SignatureMethod=HmacSHA256"
. "&AWSAccessKeyId=$private_key"
. "&Signature=".$signature
. "&SignatureVersion=2"
. "&Timestamp=" . $time;
But when i open url in new tab it's return following XML :
<ErrorResponse>
<Error>
<Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message>
</Error>
<RequestId>01a5de72-6e3f-11e4-85b3-9119f1b849cd</RequestId>
</ErrorResponse>
And it's give The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. error message when open $url link in new tab.
I dont know what's problem in creating signature??
[UPDATE]
I have try cUrl to fetch data :
$ch = curl_init();
$options = array(CURLOPT_URL => $url);
curl_setopt_array($ch, $options);
$data = curl_exec($ch);
if(!$data){
die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
curl_close($ch);
print_r($data);
But it's give me Error: "SSL certificate problem: unable to get local issuer certificate" - Code: 60. So what i do to fetch data from payments-sandbox.amazon.com
I got the same error when I tried to add my credentials with the eb init command in EB CLIx3.
It turned out I had mistyped my credentials every single time. I switched over to console for Windows where I could copy/paste my credentials. Now everything went without a hitch.
So copy/past credentials is my suggestion. If that doesn't work, you might want to create a new access key for a user with admin privileges. You can do that at the IAM section. Then try to copy past again.

Fitbit oAuth using PHP cURL - request token returns blank screen

I am trying to get issue a cURL request for "request token" method using Fitbit API. Problem is it does not show anything but a blank screen. However this process is suppose to give me an "access token" which I can use to generate a login URL to authenticate users and give access to my app.
I know there is oAuth php class for this but my server doesn't support oAuth so got to use cURL only. Please help! Many thanks in advance.
<?php
define('FITBIT_KEY', '<consumer key from fitbit website>');
define('FITBIT_SECRET', '<consumer secret from fitbit website>');
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r)); //return complete base string
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "http://api.fitbit.com/oauth/request_token";
$oauth = array( 'oauth_consumer_key' => FITBIT_KEY,
'oauth_consumer_secret' => FITBIT_SECRET,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_version' => '1.0',
'oauth_callback' => 'http://h1.servy.net/zerocuisine/index.php');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode(FITBIT_SECRET) . '&';
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$fitbit_data = json_decode($json);
echo '<pre>'.print_r($fitbit_data,true).'</pre>'; ?>
There's two problems here which lead to a blank screen. You used http instead of https in your $url. https is required for fitbit token request. You're also running json_decode on a string that's not a json array. The data inside $json is a string from http body response.
Here's my run down in detail to make it fully working below.
Instead of:
$url = "http://api.fitbit.com/oauth/request_token";
Use:
$url = "https://api.fitbit.com/oauth/request_token";
Also remove:
$fitbit_data = json_decode($json);
Change:
echo '<pre>'.print_r($json,true).'</pre>'; ?>
To:
echo '<pre>'. $json .'</pre>'; ?>
This will leave you with the successful response of:
<pre>oauth_token=93bf6ded129fcfa2b687ce6e625477af&oauth_token_secret=c9cc547ca6dd484f73763e23b0987121&oauth_callback_confirmed=true</pre>
shown into your browser.
P.S. make sure to remake this to Oauth 2.0. OAuth 1.0a support will be removed from the Fitbit Web API on April 12, 2016.

Categories