简体   繁体   中英

Twitter 401 Unauthorized — OAuth Request Token

I am using file_get_contents in PHP to make HTTP requests to the Twitter API. When trying to request a token, I get the error:

Warning: file_get_contents(https://api.twitter.com/oauth/request_token): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

Here is my code

$appID = "MY-CONSUMER-ID";
$appSecret = "MY-CONSUMER-SECRET";

$url = "https://api.twitter.com/oauth/request_token";

$oauth = array(
    "oauth_nonce" => base64_encode(time()),        
    "oauth_callback" => "MY-URL",
    "oauth_signature_method" => "HMAC-SHA1",
    "oauth_timestamp" => time(),
    "oauth_consumer_key" => $appID,
    "oauth_version" => "1.0"
);

$token_string = "POST&" . rawurlencode($url) . "&" . rawurlencode(http_build_query($oauth));
$signing_key = rawurlencode($appSecret) . "&";
$signature = base64_encode(hash_hmac("sha1", $token_string, $signing_key, true));

$oauth["oauth_signature"] = $signature;

$header = array();
foreach ($oauth as $key => $value) { $header[] = rawurlencode($key) . "=\"" . rawurlencode($value) . "\""; }
$header = implode(", ", $header);
$header = "Authorization: OAuth " . $header;
echo $header;

$opts = array('http' => array(
    'method'  => "POST",
    'header'  => $header,
) );

$context  = stream_context_create($opts);
$result = file_get_contents($url, false, $context);

You actually helped me and I'll help anyone else who reads this post.

The issue why this wasn't working was because the $oauth array must be in alphabetical order (see https://dev.twitter.com/docs/auth/creating-signature ). Thus when it is http_build_queried it was wrong.

However this helped me because my signature was passing an expected o_token when we don't at this point have one (I use this code for signing all requests) so $signing_key = rawurlencode($appSecret) . "&"; $signing_key = rawurlencode($appSecret) . "&"; helped fix my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM