使用 twitter api 获取令牌
using twitter api to get token
我正在尝试使用 Twitter api,但需要进行身份验证。有2种,我只需要Application-only authentication aka app only
。这是应用程序代表自己发出 API 请求的身份验证类型。
文档说明要使用此方法,您需要使用不记名令牌。您可以通过 POST oauth2 / token 端点传递您的消费者密钥和秘密来生成不记名令牌。
这里是link to docs explaining this endpoint。甚至还有一个示例请求,但我仍然不太清楚需要做什么。
我有一个 API 密钥和 API 密钥,但出现以下错误:
body: ‘{“errors”:[{“code”:170,“message”:“Missing required parameter:
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
对此有几件事。首先需要在服务器端发出请求。您需要从 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;
});
对于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 = try! JSONSerialization.data(withJSONObject:
["grant_type" : "client_credentials"], options: [])
我正在尝试使用 Twitter api,但需要进行身份验证。有2种,我只需要Application-only authentication aka app only
。这是应用程序代表自己发出 API 请求的身份验证类型。
文档说明要使用此方法,您需要使用不记名令牌。您可以通过 POST oauth2 / token 端点传递您的消费者密钥和秘密来生成不记名令牌。
这里是link to docs explaining this endpoint。甚至还有一个示例请求,但我仍然不太清楚需要做什么。
我有一个 API 密钥和 API 密钥,但出现以下错误:
body: ‘{“errors”:[{“code”:170,“message”:“Missing required parameter: 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
对此有几件事。首先需要在服务器端发出请求。您需要从 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;
});
对于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 = try! JSONSerialization.data(withJSONObject: ["grant_type" : "client_credentials"], options: [])