简体   繁体   English

使用 twitter api 获取令牌

[英]using twitter api to get token

I am trying to use the twitter api, but need to get authentication.我正在尝试使用 twitter api,但需要进行身份验证。 There are 2 types , and I only need Application-only authentication aka app only .有 2 种类型,我只需要Application-only authentication aka app only This is the type of authentication where an application makes API requests on its own behalf.这是应用程序代表自己发出 API 请求的身份验证类型。

The docs explain to use this method, you need to use a bearer token.文档说明要使用此方法,您需要使用不记名令牌。 You can generate a bearer token by passing your consumer key and secret through the POST oauth2 / token endpoint.您可以通过 POST oauth2 / token 端点传递您的使用者密钥和秘密来生成不记名令牌。

Here is the link to docs explaining this endpoint .这是解释此端点的文档链接 There is even an example request but still it isn't very clear to me what needs to be done.甚至还有一个示例请求,但我仍然不太清楚需要做什么。

I have an API key and API secret key, but am getting the following error:我有一个 API 密钥和 API 密钥,但出现以下错误:

body: '{“errors”:[{“code”:170,“message”:“Missing required parameter: grant_type”,“label”:“forbidden_missing_parameter”}]}' }正文:'{“错误”:[{“代码”:170,“消息”:“缺少必需参数:grant_type”,“标签”:“forbidden_​​missing_parameter”}]}'}

My server side code looks like this我的服务器端代码如下所示

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)
  });

The CURL request in the docs looks like the following:文档中的 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

To to this there were a couple of things.为此,有几件事。 First the request needed to be made server side.首先需要在服务器端发出请求。 You need to install btoa from npm to provide the encoding of the key and secret key.您需要从 npm 安装btoa以提供密钥和密钥的编码。 The KEY and SECRET need to be separated by a colon. KEY 和 SECRET 需要用冒号分隔。 The body of the request needs to be a string of请求的正文需要是一串

'grant_type=client_credentials'

See full code example below.请参阅下面的完整代码示例。

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;
  });

For Swift 5对于 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()

The problem is with the format of http body of request.问题在于请求的 http 正文的格式。 I was wrongly using dictionary of grant_type : client_credentials instead of string grant_type= client_credentials .我错误地使用了grant_type : client_credentials字典grant_type : client_credentials而不是字符串grant_type= client_credentials

request.httpBody = try! request.httpBody = 试试! JSONSerialization.data(withJSONObject: ["grant_type" : "client_credentials"], options: []) JSONSerialization.data(withJSONObject: ["grant_type" : "client_credentials"], 选项: [])

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

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