0

i tried to implement "Sign in with Twitter"
i see lots of questions at this topic here, i've read lots of them and stuck at all
i used folowing links :

implementing Sign in with Twitter
POST oauth/request_token
Creating a signature
Authorizing a request

and the result is
response : Failed to validate oauth signature and token (may be it's most often error =))

what i've done:

date_default_timezone_set('UTC');
$oauth_consumer_key = 'mYOauThConsuMerKey'; //from app settings

function generate_nonce() {
    $mt = microtime();
    $rand = mt_rand();
    return md5($mt . $rand); // md5s look nicer than numbers
}
$oauth_nonce = generate_nonce();
    $http_method = 'POST';
    $base_url = 'https://api.twitter.com/oauth/request_token';
    $oauth_signature_method = 'HMAC-SHA1';
    $oauth_timestamp = time();
    $oauth_token = 'mytokenFromAPPsettoings';
    $oauth_version = '1.0';
$oauth_callback = 'http://twoends.home/backend';
    $params = array(
        rawurlencode('oauth_nonce')=>rawurlencode($oauth_nonce),
        rawurlencode('oauth_callback')=>rawurlencode($oauth_callback),
        rawurlencode('oauth_signature_method')=>rawurlencode($oauth_signature_method),
        rawurlencode('oauth_timestamp')=>rawurlencode($oauth_timestamp),
        rawurlencode('oauth_token')=>rawurlencode($oauth_token),
        rawurlencode('oauth_version')=>rawurlencode($oauth_version),
    );

    ksort($params);
    $parameter_string = http_build_query($params,'','&');
        $base_string  = strtoupper($http_method).'&';
        $base_string .= rawurlencode($base_url).'&';
        $base_string .= rawurlencode($parameter_string);

        $oauth_consumer_secret = 'myappconsumersecret';
        $oauth_token_secret = 'mytokensecret';
$oauth_signing_key =rawurlencode($oauth_consumer_secret).'&'.rawurlencode($oauth_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_string, $oauth_signing_key, true));
$DST ='OAuth ';
foreach($params as $key=>$value){
    $DST .= $key.'='.'"'.$value.'"&';
}
$DST = rtrim($DST,'&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $base_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$DST));
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

so,this code was struggled much and it still produces error
in one topic i've read that token isn't needed on this stage : with it or without - nothing matters - still same error
tried to play with time (set UTC) - same error
also i tried to use someones working code like this but that didn't work for me
why i'm not using someones lib - because i want to go through algo step-by-step, but i'm tired with it and neeed help

thx in advance, any help appreciated, may be got an example of working step-by-step guide ?

0

i'd like to take a new look at a problem and post new data
thanks to @Jonny S i found few mistakes and got another error =)

so, my workflow now looks:

function to generate nonce,additional info: oauth_nonce in api, oauth.net

function generate_nonce() {
    $mt = microtime();
    $rand = mt_rand();

    return md5($mt . $rand); // md5s look nicer than numbers
}

Implementing Sign in with Twitter (this link shows us what header we should POST in advance) and shows us direction to move - POST oauth/request_token
this page links with oauth docs section 6.1
there we can find what parameters are needed to request token, but in official docs you would not find "oauth_calback" param which is a required param in twitter API!

the next step i do - collecting needed params:

  • oauth_consumer_key

    $oauth_consumer_key = 'YoUrS KEy FrOm aPP ApI';
    
  • oauth_nonce

    $oauth_nonce = generate_nonce();
    
  • oauth_callback

    $oauth_callback = 'http://twoends.home/backend';
    
  • oauth_sinature_method

    $oauth_signature_method = 'HMAC-SHA1';
    
  • oauth_timestamp

    $oauth_timestamp = time();
    
  • oauth_version

    $oauth_version = '1.0';
    
  • additional parameters (needed in process):

  • OAuth Signature (the most tricky part)

here we have an API page on how to do it Creating a signature

first we need to collect all needed params together,percent encode and sort them, i pushed them to array:

    $params = array(
        rawurlencode('oauth_consumer_key')=>rawurlencode($oauth_consumer_key),
        rawurlencode('oauth_nonce')=>rawurlencode($oauth_nonce),
        rawurlencode('oauth_callback')=>rawurlencode($oauth_callback),
        rawurlencode('oauth_signature_method')=>rawurlencode($oauth_signature_method),
        rawurlencode('oauth_timestamp')=>rawurlencode($oauth_timestamp),
        rawurlencode('oauth_version')=>rawurlencode($oauth_version),
    );

and then sort:

    ksort($params);

then i'm creating parameter string:

    $parameter_string = http_build_query($params,'','&');

result:

param string :oauth_callback=http%253A%252F%252Ftwoends.home%252Fbackend&oauth_consumer_key=oauth_consumer_key_wQjQ7u5lgwA&oauth_nonce=46fa649c21ac5315d4d4510ff68ad630&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1381930918&oauth_version=1.0

next i need to create base_string, which will be used to create signature as data param for hash_hmac() function

    $base_string = strtoupper($http_method).'&';
    $base_string .= rawurlencode($base_url).'&';
    $base_string .= rawurlencode($parameter_string);

result:

POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%25253A%25252F%25252Ftwoends.home%25252Fbackend%26oauth_consumer_key%3Dapp_cons_keyQjQ7u5lgwA%26oauth_nonce%3D46fa649c21ac5315d4d4510ff68ad630%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1381930918%26oauth_version%3D1.0

next i get consumer_secret from APP settings to create signing key which will be used to create signature as a third param at hash_hmac() function

    $oauth_consumer_secret = 'consumer_secret_from_app_settings';
    $oauth_signing_key = rawurlencode($oauth_consumer_secret).'&';

one thing to mention: in 1st step (request_token we don't need to put any token)

this step creates signature:

    $oauth_signature = base64_encode(hash_hmac('sha1', $base_string, $oauth_signing_key, true));

now we need to add signature to params array and build header string

    $params['oauth_signature'] = rawurlencode($oauth_signature);
    ksort($params);

building header string can be found at Building the header string

    $DST ='OAuth ';
    foreach($params as $key=>$value){
        $DST .= $key.'='.'"'.$value.'", ';
    }
    $DST = rtrim($DST,', ');

    //or we can make it by hand as below

    //$DST .= 'oauth_nonce="'.rawurlencode($oauth_nonce)
    //     .'", oauth_callback="'.rawurlencode($oauth_callback)
    //     .'", oauth_signature_method="HMAC-SHA1", oauth_timestamp="'
    //     .rawurlencode($oauth_timestamp).'", oauth_consumer_key="'
    //     .rawurlencode($oauth_consumer_key).'", oauth_signature="'
    //     .rawurlencode($oauth_signature).'", oauth_version="1.0"';

the final step (i hope) is to send a request:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $base_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$DST));
    curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    echo '<pre>';
        print_r($info);
    echo '</pre>';

this code produces error 400 - bad request
if i remove curl_setopt($ch, CURLOPT_POST, true); i get error - 401
request info dump :

Array
(
    [url] => https://api.twitter.com/oauth/request_token
    [content_type] => 
    [http_code] => 400
    [header_size] => 66
    [request_size] => 471
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.710993
    [namelookup_time] => 0.081279
    [connect_time] => 0.23482
    [pretransfer_time] => 0.550913
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 0
    [upload_content_length] => -1
    [starttransfer_time] => 0.710976
    [redirect_time] => 0
    [redirect_url] => 
    [primary_ip] => 199.16.156.104
    [certinfo] => Array
    (
    )

    [primary_port] => 443
    [local_ip] => 192.168.1.234
    [local_port] => 54994
    [request_header] => POST /oauth/request_token HTTP/1.1
Host: api.twitter.com
Accept: */*
Authorization: OAuth oauth_callback="http%3A%2F%2Ftwoends.home%2Fbackend", oauth_consumer_key="your_consumer_keyCwQjQ7u5lgwA", oauth_nonce="1ba83f0af239f439c1524096c33faefe", oauth_signature="QZZvrJ8wzCQOYhiKJeT4vz%2FWCcg%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1381931941", oauth_version="1.0"
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue


)

hope this will help to understand where to find the error, in advance i'll also try to use Fiddler to trace request

---------------------------------------
solved by using new API

  • used new API POST oauth2/token and it took me a few minutes to make it work, i guess it should be some notice in old API about its usefullness – alexZT Oct 17 '13 at 8:39
  • 1
    The oauth2 bearer token is fine if you only want to make requests on behalf of your application. If you want to be able to perform actions on behalf of another user, you will still need to use oauth 1.0a. – Jon Susiak Oct 17 '13 at 9:51
0

It looks like the oauth_callback url is being triple encoded in the basestring. It should be of the form:

POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&
oauth_callback%3Dhttp%253A%252F%252Ftwoends.home%252Fbackend%26
oauth_consumer_key%3Dapp_cons_keyQjQ7u5lgwA ...

In your basestring:

oauth_callback%3Dhttp%25253A%25252F%25252Ftwoends.home%25252Fbackend

The culprit appears to be 'http_build_query'.

  • thanks for advices, i used new API and oauth2 and it works! i guess that was the reason, and thanks for fiddler - cool thing=) – alexZT Oct 17 '13 at 8:44
  • 1
    The oauth2 bearer token is fine if you only want to make requests on behalf of your application. If you want to be able to perform actions on behalf of another user, you will still need to use oauth 1.0a. – Jon Susiak Oct 17 '13 at 8:59
  • excluded 'http_build_query' : $params = array( 'oauth_consumer_key'=>$oauth_consumer_key, 'oauth_nonce'=>$oauth_nonce, 'oauth_callback'=>$oauth_callback, 'oauth_signature_method'=>$oauth_signature_method, 'oauth_timestamp'=>$oauth_timestamp, 'oauth_version'=>$oauth_version, ); $parameter_string = ''; foreach($params as $key=>$param){ $parameter_string .= rawurlencode($key).'&'.rawurlencode($param); } $parameter_string = rtrim($parameter_string,'&'); – alexZT Oct 17 '13 at 10:08
  • and it's still bad. I continue digging it =) – alexZT Oct 17 '13 at 10:10
  • shouldn't it be: $parameter_string .= rawurlencode($key).'='.rawurlencode($param).'&'; – Jon Susiak Oct 17 '13 at 10:24
0

There appear to be several things wrong with your code:

1) Your params array should contain oauth_consumer_key instead of oauth_token

$params = array(
    rawurlencode('oauth_nonce')=>rawurlencode($oauth_nonce),
    rawurlencode('oauth_callback')=>rawurlencode($oauth_callback),
    rawurlencode('oauth_signature_method')=>rawurlencode($oauth_signature_method),
    rawurlencode('oauth_timestamp')=>rawurlencode($oauth_timestamp),
    rawurlencode('oauth_consumer_key')=>rawurlencode($oauth_consumer_key),
    rawurlencode('oauth_version')=>rawurlencode($oauth_version),
);

2) Your signing key for a request token should be constructed using oauth_consumer_secret followed by an ampersand:

$oauth_signing_key =rawurlencode($oauth_consumer_secret).'&';

3) You don't appear to be setting the signature anywhere in the Authorization header. Do:

$DST ='OAuth ';
foreach($params as $key=>$value){
    $DST .= $key.'='.'"'.$value.'"&';
}
$DST .= 'oauth_signature='.rawurlencode($oauth_signature)
  • 1 - my mistake,it exists, oauth_token also was there-i dropped it. 2 - replaced signing key with yours. 3 - added signature to $params $params['oauth_signature'] = rawurlencode($oauth_signature). Result: [request_header] => GET /oauth/request_token HTTP/1.1 Host: api.twitter.com Accept: */* Authorization: OAuth oauth_callback="http%3A%2F%2Ftwoends.home%2Fbackend"&oauth_consumer_key="consumer_key"&oauth_nonce="45ed597e5456715d6880cf73d702a7df"&oauth_signature="5ap7idjtbcdlBAeAx3HSVQpLqBk%3D"&oauth_signature_method="HMAC-SHA1"&oauth_timestamp="1381843238"&oauth_version="1.0" still fails – alexZT Oct 15 '13 at 13:34
  • as i wrote the answer - saw that header sends via GET request, added option curl_setopt($ch, CURLOPT_POST, true); and now i'm receiving http error - 400, but don't receive - "Failed to validate oauth signature and token " – alexZT Oct 15 '13 at 13:47
  • I think I see the problem. In the Authorization header the parameters should be separated by a comma and a space rather than an ampersand. ($DST .= $key.'='.'"'.$value.'", ';) – Jon Susiak Oct 15 '13 at 14:41
  • you're quite right, i fixed it and now i get header: ` [request_header] => POST /oauth/request_token HTTP/1.1 Host: api.twitter.com Accept: / Authorization: OAuth oauth_callback="http%3A%2F%2Ftwoends.home%2Fbackend", oauth_consumer_key="encoded_consumer_key", oauth_nonce="0cd119c053e5787ca77d8589d59975d1", oauth_signature="WeAeM%2FR1SQZbwlg0zR_signature", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1381907960", oauth_version="1.0" Content-Length: -1 Content-Type: application/x-www-form-urlencoded Expect: 100-continue`, still err 400 - Bad request – alexZT Oct 16 '13 at 7:22
  • so, i get two errors: 400 if curl_setopt($ch, CURLOPT_POST, true);, and 401 if without it. If i look in POST oauth/request_token - it accepts both GET or POST, i can't imagine why it differs so much – alexZT Oct 16 '13 at 7:26

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.