Twitter OAuth session timeout - php

I am trying this sample code from this link. Currently, I can authorize but after i authorize the app, its showing me
Your session has timed out
What error is this actually? I tried searching in the internet but i couldnt found any solution for this. I just copied the full code and change the API key to my app API key.
This is my php code:
<?php
// Initiate the authorization process by sending a signed request to Twitter
// for a Request Token and then redirect the user to Twitter to authorize the
// application.
require "../include/oauthvalues.php";
session_start();
$oauthTimestamp = time();
$nonce = md5(mt_rand());
echo time();
// prepare the signature string
$sigBase = "GET&" . rawurlencode($requestTokenUrl) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($consumerKey)
. "&oauth_nonce=" . rawurlencode($nonce)
. "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
. "&oauth_timestamp=" . $oauthTimestamp
. "&oauth_version=" . $oauthVersion);
// prepare the signature key
$sigKey = $consumerSecret . "&";
$oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));
// send the signed request and receive Twitter's response
$requestUrl = $requestTokenUrl . "?"
. "oauth_consumer_key=" . rawurlencode($consumerKey)
. "&oauth_nonce=" . rawurlencode($nonce)
. "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
. "&oauth_timestamp=" . rawurlencode($oauthTimestamp)
. "&oauth_version=" . rawurlencode($oauthVersion)
. "&oauth_signature=" . rawurlencode($oauthSig);
$response = file_get_contents($requestUrl);
// extract and preserve the request tokens
parse_str($response, $values);
$_SESSION["requestToken"] = $values["oauth_token"];
$_SESSION["requestTokenSecret"] = $values["oauth_token_secret"];
// send the user to Twitter to grant authorization
$redirectUrl = $authorizeUrl . "?oauth_token=" . $_SESSION["requestToken"];
header("Location: " . $redirectUrl);

Related

Using OAuth 1.0 with PHP cUrl

I am working on a small PHP script which calls an API. This API uses OAuth 1.0 authorization. Hence I need to create the signature and request-header. I am pretty sure my signature-generation method and the generation of the request-header work well as I have done the same in C# (where the everything works) and the signature as well as the header look quite the same.
Generating signature:
function generateSignature($method,$url,$consumerKey,$consumerSecret,$tokenValue,$tokenSecret,$timestamp, $nonce, $signatureMethod, $version)
{
$base = $method . "&" . rawurlencode($url) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($consumerKey)
. "&oauth_nonce=" . rawurlencode($nonce)
. "&oauth_signature_method=" . rawurlencode($signatureMethod)
. "&oauth_timestamp=" . rawurlencode($timestamp)
. "&oauth_token=" . rawurlencode($tokenValue)
. "&oauth_version=" . rawurlencode($version));
$key = rawurlencode($consumerSecret) . '&' . rawurlencode($tokenSecret);
$signature = base64_encode(hash_hmac('sha1', $base, $key, true));
return $signature;
}
Generating authorization header:
$authHeader = "OAuth realm="."\"\","."
oauth_consumer_key=\"{$consumerKey}\",
oauth_nonce=\"{$nonce}\",
oauth_signature_method=\"{$signatureMethod}\",
oauth_timestamp=\"{$timestamp}\",
oauth_token=\"{$tokenValue}\",
oauth_version=\"{$version}\",
oauth_signature=\"{$signature}\"";
I got stuck at the point of passing the authorization header over to the API I am calling.
Setting the authorization:
$header = array('Content-Type: application/x-www-form-urlencoded');
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
curl_setopt($ch, CURLOPT_POSTFIELDS,urlencode($authHeader));
Finally, when I make the request I get the response, that a parameter is missing.

Oauth signature, REST API

I am attempting to access the fat secret API.
https://platform.fatsecret.com/api/
I am attempting to create an Oauth signature using the secret key given by fat secret. When I try access the URL to grab the data I get an error saying my Oauth signature is invalid.
I create the signiture using base64_encode and then hash hmac using sha1.
Here is my code with the secret key blanked out, am I creating the signature in an incorrect way? Or can anyone see where I am going wrong.
Thank you
<?php
$requestTokenUrl = "http://platform.fatsecret.com/rest/server.api";
$oauth_consumer_key = "925f5e1a8b674a70b52eabf15f3265e7";
$nonce = md5(mt_rand());
$outh_signature = '';
$oauthSignatureMethod = "HMAC-SHA1";
$oauthTimestamp = time();
$oauthVersion = "1.0";
$secret_key = "My Secret Key";
$sigKey= $consumer_key . "&";
$sigBase = "method=food.get" . rawurlencode($requestTokenUrl) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($oauth_consumer_key)
. "&oauth_nonce=" . rawurlencode($nonce)
. "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
. "&oauth_timestamp=" . $oauthTimestamp
. "&oauth_version=" . $oauthVersion);
$oauthSig = base64_encode(hash_hmac('sha1', $secret_key, true));
$requestUrl = $requestTokenUrl . "?"
. "food_id=33691"
. "&method=food.get"
. "&oauth_consumer_key=" . rawurlencode($oauth_consumer_key)
. "&oauth_nonce=" . rawurlencode($nonce)
. "&oauth_signature=" . rawurlencode($oauthSig)
. "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
. "&oauth_timestamp=" . rawurlencode($oauthTimestamp)
. "&oauth_version=" . rawurlencode($oauthVersion);
var_dump($requestUrl);

Twitter Streaming 401 Unauthorized OAuth

I'm trying to create a script that uses the twitter streaming api to keep a tab on tweets with a certain hash-tag.
Whenever I try creating a request though, I always get a 401 Unauthorized return. Can anyone help me figure out what I'm doing incorrectly?
I tried to follow twitter's api to the dot, but apparently I'm doing something wrong. The code I have is below.
$base_url_string = urlencode($base_url);
$parameter_string = urlencode('oauth_consumer_key') . '=' . urlencode($consumer_key) . '&'
. urlencode('oauth_nonce') . '=' . urlencode($nonce) . '&'
. urlencode('oauth_signature_method') . '=' . urlencode($signature_method) . '&'
. urlencode('oauth_timestamp') . '=' . urlencode($timestamp) . '&'
. urlencode('oauth_token') . '=' . urlencode($token) . '&'
. urlencode('oauth_version') . '=' . urlencode($version) . '&'
. urlencode('track') . '=' . urlencode('#kitten');
$signature_base_string = $method . "&" . $base_url_string . "&" . urlencode($parameter_string);
$signature = base64_encode(hash_hmac('sha1', $signature_base_string, $secret, true));
$fp = fsockopen("ssl://stream.twitter.com", 443, $errno, $errstr, 30);
if (!$fp) {
print "$errstr ($errno)\n";
} else {
$request = $method . " /1.1/statuses/filter.json?" . urlencode("track") . "=" . urlencode("#kitten") . " HTTP/1.1\r\n";
$request .= "Host: stream.twitter.com\r\n";
$request .= 'Authorization: OAuth'
. ' oauth_consumer_key="' . $consumer_key . '",'
. ' oauth_nonce="' . $nonce . '",'
. ' oauth_signature="' . $signature . '",'
. ' oauth_signature_method="' . $signature_method . '",'
. ' oauth_timestamp="' . $timestamp . '",'
. ' oauth_token="' . $token . '",'
. ' oauth_version="' . $version . '"'
. "\r\n\r\n";
print $request . "</br>";
fwrite($fp, $request);
while (!feof($fp)) {
$json = fgets($fp);
echo $json;
$data = json_decode($json, true);
if ($data) {
print $data;
}
}
print 'exiting...';
fclose($fp);
}
Ok so I figured this all out. It was a combination of poor string manipulation and not Percent Encoding everything. Both the keys and values of the OAuth string must be Percent encoded. I had done that in the signature, but not in the actual request. Once I fixed that, the request got through and I was connected to the Twitter Streaming API.

Google API Get inbox emails using access_token?

I am able to get access_token for multiple permissions like emails, contacts, docs, etc. using oAuth 2.0. I have access_token
I got contacts using the following code.
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max- results='.$max_results.'&oauth_token='.$access_token;
$response_contacts= curl_get_file_contents($url);
Now i want to get users Emails using this access_token.
i used this url . but it gives 401 unauthorized Error
$url = 'https://mail.google.com/mail/feed/atom&oauth_token='.$access_token;
$response_emails= curl_get_file_contents($url);
please guide me how can i get emails using access_token.
I've seen references to the Gmail feed using oauth_token as a request parameter. However, once I used the OAuth Playground I discovered that you need to pass your OAuth information as an Authorization header, as you'll see below.
<?php
$now = time();
$consumer = ...; // your own value here
$secret = ...; // your own value here
$nonce = ...; // same value you've been using
$algo = "sha1";
$sigmeth = "HMAC-SHA1";
$av = "1.0";
$scope = "https://mail.google.com/mail/feed/atom";
$path = $scope;
$auth = ...; // an object containing outputs of OAuthGetAccessToken
$args = "oauth_consumer_key=" . urlencode($consumer) .
"&oauth_nonce=" . urlencode($nonce) .
"&oauth_signature_method=" . urlencode($sigmeth) .
"&oauth_timestamp=" . urlencode($now) .
"&oauth_token=" . urlencode($auth->oauth_token) .
"&oauth_version=" . urlencode($av);
$base = "GET&" . urlencode($path) . "&" . urlencode($args);
$sig = base64_encode(hash_hmac($algo, $base,
"{$secret}&{$auth->oauth_token_secret}", true));
$url = $path . "?oauth_signature=" . urlencode($sig) . "&" . $args;
// Create a stream
$opts = array(
"http" => array(
"method" => "GET",
"header" => "Authorization: OAuth " .
"oauth_version=\"{$av}\", " .
"oauth_nonce=\"{$nonce}\", " .
"oauth_timestamp=\"{$now}\", " .
"oauth_consumer_key=\"{$consumer}\", " .
"oauth_token=\"{$auth->oauth_token}\", " .
"oauth_signature_method=\"{$sigmeth}\", " .
"oauth_signature=\"{$sig}\"\r\n"
)
);
$context = stream_context_create($opts);
$out = file_get_contents($path, false, $context);
?>

401 error when requesting OAuth access credentials using Codeigniter

So I'm putting together a quick and dirty app to add new posts automatically to Tumblr based on new items pulled from an RSS feed. The app is in Codeigniter, and so far I've managed to obtain the request credentials and sent the user to Tumblr for authorisation. The problem is, once they're redirected back to the app and I make a request for the access credentials, I'm getting the following error:
Message: file_get_contents(http://www.tumblr.com/oauth/access_token?oauth_consumer_key=THECONSUMERKEY&oauth_nonce=9362afdd34f9ce1601fb9cf505ffa3cf&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1327440390&oauth_token=09mFsxCvsODDmSxPCyQNu4QKFMMXaAEEyPtBibPUyUTE1n2BsJ&oauth_verifier=hDfGgesf9EKIO5yFhiHxtnsbP42XEP1FISY2qyyWerzXf6fPTG&oauth_version=1.0&oauth_signature=yeFw8ACvVvKtD%2BQ%2FdzbLivDSm1Y%3D) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
Here's the code I'm using:
$oauthVerifier = $_GET["oauth_verifier"];
$sigBase = "GET&" . rawurlencode($this->accessTokenUrl) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($this->consumerKey)
. "&oauth_nonce=" . rawurlencode($this->nonce)
. "&oauth_signature_method=" . rawurlencode($this->oauthSignatureMethod)
. "&oauth_timestamp=" . $this->oauthTimestamp
. "&oauth_token=" . rawurlencode($this->CI->session->userdata('requestToken'))
. "&oauth_verifier=" . rawurlencode($oauthVerifier)
. "&oauth_version=" . $this->oauthVersion);
$sigKey = $this->consumerSecret . "&";
$oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));
$requestUrl = $this->accessTokenUrl . "?"
. "oauth_consumer_key=" . rawurlencode($this->consumerKey)
. "&oauth_nonce=" . rawurlencode($this->nonce)
. "&oauth_signature_method=" . rawurlencode($this->oauthSignatureMethod)
. "&oauth_timestamp=" . rawurlencode($this->oauthTimestamp)
. "&oauth_token=" . rawurlencode($this->CI->session->userdata('requestToken'))
. "&oauth_verifier=" . rawurlencode($oauthVerifier)
. "&oauth_version=" . rawurlencode($this->oauthVersion)
. "&oauth_signature=" . rawurlencode($oauthSig);
$response = file_get_contents($requestUrl);
Any bright ideas?
This is incomplete and needs some bug chasing by you.
Do understand the relevant part of the conversation:
TumApp to user: please go to Tumblr with one of my request tokens: GHF3F4F
user to Tumblr: I authorize TumApp, and here is it's request token: GHF3F4F
Tumblr to itself: let me authorize GHF3F4F, which TumApp can exchange for an access token
to user: redirect to Tumapp's callback
Tumapp to itself: Great, user authorized me (by requesting my callback). Let me exchange my request token for an access token
to Tumblr: Hey, give me an access token for GHF3F4F
Tumblr to Tumapp: Epic 401 fail!
Here are the reasons why Tumblr would give a 401
From http://oauth.net/core/1.0a/#http_codes
HTTP 401 Unauthorized
Invalid Consumer Key
Invalid / expired Token
Invalid signature
Invalid / used nonce
I would deduce starting with the token; the consumer key successfully got you a request token and the signature and nonce are generated by the library.
UPDATE: The stray ampersand was actually not in the original code (my bad), but something I did afterwards when trying to fix it. In fact, the cause of the original problem was the absence of the Request Token Secret in the signature key.
Thanks for the pointers, aitchnyu - in the end, the problem was a stray ampersand. In the signature base, I wrapped the ampersand before "oauth_consumer_key=" in a rawurlencode, when it should have come before it.
Here's the old sig base:
"GET&" . rawurlencode($this->accessTokenUrl)
. rawurlencode("&oauth_consumer_key=" . rawurlencode($this->consumerKey)
. "&oauth_nonce=" . rawurlencode($this->nonce)
. "&oauth_signature_method=" . rawurlencode($this->oauthSignatureMethod)
. "&oauth_timestamp=" . rawurlencode($this->time)
. "&oauth_token=" . rawurlencode($token)
. "&oauth_verifier=" . rawurlencode($oauthVerifier)
. "&oauth_version=" . $this->oauthVersion);
The new one:
"GET&" . rawurlencode($this->accessTokenUrl) . "&"
. rawurlencode("oauth_consumer_key=" . rawurlencode($this->consumerKey)
. "&oauth_nonce=" . rawurlencode($this->nonce)
. "&oauth_signature_method=" . rawurlencode($this->oauthSignatureMethod)
. "&oauth_timestamp=" . rawurlencode($this->time)
. "&oauth_token=" . rawurlencode($token)
. "&oauth_verifier=" . rawurlencode($oauthVerifier)
. "&oauth_version=" . $this->oauthVersion);
Vital difference!

Categories