首页 > 解决方案 > Node 环境中的 Twitter 应用程序身份验证,React

问题描述

以下来自其他帖子的代码: Twitter 1.1 OAuthauthentity_token_error(99)https://gist.github.com/lgladdy/5141615 <-- Life saver 等。

我已确定: - 我已退出 Twitter。- 请求包含它需要的所有内容。- 我通过 chrome 插件启用了 CORS。- Base64 编码的密钥匹配。

我仍然收到“代码”:99,“消息”:“无法验证您的凭据”。当我使用 CURL 和 PHP 更改请求中的任何参数时,我可以重现此 99 错误。所以 React 代码一定有问题。我找不到代码的 javascript 工作版本。

卷曲作品:

curl --request 'POST' 'https://api.twitter.com/oauth2/token' --header 'Authorization: Basic ENCODED_KEY+ENCODED_SECRET, Content-Type: "application/x-www-form-urlencoded;charset=UTF-8"' --data "grant_type=client_credentials" --verbose

PHP - 文档工作:

<?php
//This is all you need to configure.
$app_key = 'KEY';
$app_token = 'SECRET';
//These are our constants.
$api_base = 'https://api.twitter.com/';
$bearer_token_creds = base64_encode($app_key.':'.$app_token);
//Get a bearer token.
$opts = array(
  'http'=>array(
    'method' => 'POST',
    'header' => 'Authorization: Basic '.$bearer_token_creds."\r\n".
               'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
    'content' => 'grant_type=client_credentials'
  )
);
$context = stream_context_create($opts);
$json = file_get_contents($api_base.'oauth2/token',false,$context);
$result = json_decode($json,true);
if (!is_array($result) || !isset($result['token_type']) || !isset($result['access_token'])) {
  die("Something went wrong. This isn't a valid array: ".$json);
}
if ($result['token_type'] !== "bearer") {
  die("Invalid token type. Twitter says we need to make sure this is a bearer.");
}
//Set our bearer token. Now issued, this won't ever* change unless it's invalidated by a call to /oauth2/invalidate_token.
//*probably - it's not documentated that it'll ever change.
$bearer_token = $result['access_token'];
//Try a twitter API request now.
$opts = array(
  'http'=>array(
    'method' => 'GET',
    'header' => 'Authorization: Bearer '.$bearer_token
  )
);
$context = stream_context_create($opts);
$json = file_get_contents($api_base.'1.1/statuses/user_timeline.json?count=1&screen_name=lgladdy',false,$context);
$tweets = json_decode($json,true);
echo "@lgladdy's last tweet was: ".$tweets[0]['text']."\r\n";
echo $bearer_token_creds;

?>

反应 99 错误:

var R = require('request'); //default React
    var consumer_key = 'KEY';
    var consumer_secret = 'SECRET';
    var encode_secret = new Buffer(consumer_key + ':' + consumer_secret).toString('base64');
    console.log('encode_secret', encode_secret)
R({
      url: 'https://api.twitter.com/oauth2/token',
      method: 'POST',
      header: {
        'Authorization': 'Basic ' + encode_secret,
        'Content-Type': "application/x-www-form-urlencoded;charset=UTF-8"
      },
      content: "grant_type=client_credentials"

    }, function (err, resp, body) {

      console.log("B1", body); // <<<< This is your BEARER TOKEN !!
      console.log("R1", resp);
      console.log("E1", err);
    });

有人可以帮忙吗?

标签: node.jsreactjsapitwitter-oauth

解决方案


  • 数据应该是一个字符串而不是一个对象。
  • 由于 CORS,客户端不支持,即使 CORS chrome 扩展也不起作用。
  • 下面是工作的 Node JS 代码。

工作节点JS代码:

const http = require('http');
const axios = require('axios');


http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });

  var consumer_key = 'YOUR_KEY';
  var consumer_secret = 'YOUR_SECRET';
  var encode_secret = new Buffer(consumer_key + ':' + consumer_secret).toString('base64');

  var url = "https://api.twitter.com/oauth2/token"

  var data = "grant_type=client_credentials"

  var options = {
    headers: {
      'Authorization': 'Basic ' + encode_secret,
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    }  
  };

  axios.post(url,data,options)
  .then(result => console.log("success", result))
  .catch(error => console.log("error", error))

}).listen(8080);

推荐阅读