简体   繁体   English

Twitter 401未经授权-OAuth请求令牌

[英]Twitter 401 Unauthorized — OAuth Request Token

I am using file_get_contents in PHP to make HTTP requests to the Twitter API. 我在PHP中使用file_get_contents向Twitter API发出HTTP请求。 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 ). 为什么不起作用的问题是因为$ oauth数组必须按字母顺序排列(请参阅https://dev.twitter.com/docs/auth/creating-signature )。 Thus when it is http_build_queried it was wrong. 因此,当它是http_build_queried时,这是错误的。

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) . "&"; 但这对我有所帮助,因为当我们此时没有一个签名时(我使用此代码对所有请求进行签名),我的签名传递了预期的o_token,因此$signing_key = rawurlencode($appSecret) . "&"; $signing_key = rawurlencode($appSecret) . "&"; helped fix my problem. 帮助解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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