我正在尝试使用 twitter api,但需要获得身份验证。有2种类型,我只需要Application-only authentication aka app only
。这是应用程序代表自己发出 API 请求的身份验证类型。
文档解释说要使用此方法,您需要使用不记名令牌。您可以通过 POST oauth2/token 端点传递您的消费者密钥和秘密来生成不记名令牌。
这里是解释此端点的文档链接 https://developer.twitter.com/en/docs/basics/authentication/overview/application-only。甚至有一个示例请求,但我仍然不太清楚需要做什么。
我有 API 密钥和 API 密钥,但收到以下错误:
body: ‘{“errors”:[{“code”:170,“message”:“缺少必需参数:
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