使用Twitter API获取令牌

时间:2018-10-22 08:09:45

标签: javascript twitter ecmascript-6 twitter-oauth

我正在尝试使用twitter api,但需要进行身份验证。有2种类型,我只需要Application-only authentication aka app only。这是一种身份验证,其中应用程序代表自己发出API请求。

文档说明要使用此方法,您需要使用不记名令牌。您可以通过将消费者密钥和机密传递到POST oauth2 /令牌端点来生成承载令牌。

这里是link to docs explaining this endpoint。甚至有一个示例请求,但我仍然不清楚需要做什么。

我有一个API密钥和API秘密密钥,但是出现以下错误:

  

正文:‘{“错误”:[{“代码”:170,“消息”:“缺少必需的参数:   grant_type”,“ label”:“ forbidden_​​missing_parameter”}]}’}

我的服务器端代码如下

var request = require('request');
var btoa = require('btoa');

const KEY = encodeURIComponent('1234');
const SECRET = encodeURIComponent('5678');

request({
    headers: {
      'Authorization': 'Basic ' + btoa(`${KEY}:${SECRET}`),
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    uri: 'https://api.twitter.com/oauth2/token',
    method: 'POST',
    body:  JSON.stringify({
      'grant_type': 'client_credentials' // I am passing the grant_type here
    })
  }, function (err, res, body) {
    console.log('res', res)
  });

文档中的CURL请求如下所示:

POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic eHZ6MWV2R ... o4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip

grant_type=client_credentials

2 个答案:

答案 0 :(得分:2)

为此,有两件事。首先,需要将请求发送到服务器端。您需要从npm安装btoa来提供密钥和秘密密钥的编码。 KEY和SECRET需要用冒号分隔。请求的正文必须为字符串

'grant_type=client_credentials'

请参阅下面的完整代码示例。

const btoa = require('btoa');

request({
    headers: {
      'Authorization': 'Basic ' + btoa(`${KEY}:${SECRET}`),
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    uri: 'https://api.twitter.com/oauth2/token',
    method: 'POST',
    body: 'grant_type=client_credentials'
  }, (error, response, body) => {
    const token = JSON.parse(body).access_token;
  });

答案 1 :(得分:1)

对于Swift 5

        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)

        let info = Bundle.main.infoDictionary
        let twitterConsumerKey : String = (info?["TwitterConsumerKey"] as? String)!
        let twitterConsumerSecret : String = (info?["TwitterConsumerSecret"] as? String)!

        let loginString = String(format: "%@:%@", twitterConsumerKey, twitterConsumerSecret)
        let loginData = loginString.data(using: String.Encoding.utf8)!
        let base64LoginString = loginData.base64EncodedString()

        let urlString = NSString(format: "https://api.twitter.com/oauth2/token");
        print("url string is \(urlString)")
        let request : NSMutableURLRequest = NSMutableURLRequest()
        request.url = NSURL(string: NSString(format: "%@", urlString)as String) as URL?
        request.httpMethod = "POST"
        request.timeoutInterval = 30
        request.httpBody = "grant_type=client_credentials".data(using: String.Encoding.utf8)!

        request.addValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.addValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

        let dataTask = session.dataTask(with: request as URLRequest) {data, response, error -> Void in
            guard let httpResponse = response as? HTTPURLResponse,
                let receivedData = data else {
                    print("error: not a valid http response")
                    return
            }

            switch (httpResponse.statusCode)
            {
            case 200:

                let response = NSString (data: receivedData, encoding: String.Encoding.utf8.rawValue)


                if response == "SUCCESS"
                {

                }

            default:
                print("save profile POST request got response \(httpResponse.statusCode)")
                let str = String(decoding:data!, as: UTF8.self)

                print(str)

            }
        }
        dataTask.resume()

问题在于请求的http正文的格式。我错误地使用了grant_type : client_credentials的字典而不是字符串grant_type= client_credentials

  

request.httpBody =试试! JSONSerialization.data(withJSONObject:   [“ grant_type”:“ client_credentials”],选项:[])