我正在尝试发布一条推文,但由于某种原因它没有按预期工作。
我怀疑这个问题可能与signature
字符串有关,但遵循twitter根据signing所说的内容请求看起来没问题。
这是我的代码:
function postTweet(user_id, AccessToken, AccessTokenSecret) {
var base_url = 'https://api.twitter.com/1.1/statuses/update.json',
oauth_nonce = randomString(),
oauth_signature,
oauth_timestamp = Math.floor(new Date().getTime() / 1000),
reqArray,
req,
signature_base_string,
signing_key;
reqArray = [
"include_entities=true",
'oauth_consumer_key="' + CONFIG.TWITTER_CONSUMER_KEY + '"',
'oauth_nonce="' + oauth_nonce + '"',
'oauth_signature_method="HMAC-SHA1"',
'oauth_timestamp="' + oauth_timestamp + '"',
'oauth_token="' + AccessToken + '"',
'oauth_version="1.0"',
'status=' + encodeURIComponent("hello world")
];
req = reqArray.sort().join('&');
signature_base_string = "POST&" + encodeURIComponent(base_url) + "&" + encodeURIComponent(req);
signing_key = CONFIG.TWITTER_CONSUMER_KEY_SECRET + '&' + AccessTokenSecret;
oauth_signature = encodeURIComponent(CryptoJS.HmacSHA1(signature_base_string, signing_key).toString(CryptoJS.enc.Base64));
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: 'hello world'
}).then(function (response) {
return response;
}).catch(function (error) {
console.log(error);
});
}
作为回应,我明白:
更新
考虑到在我的项目中我已经有了 $cordovaOauthUtility
我开始这样使用它:
function postTweet(accessToken, accessTokenSecret) {
var params, signature;
params = {
include_entities: true,
oauth_consumer_key: CONFIG.TWITTER_CONSUMER_KEY,
oauth_nonce: $cordovaOauthUtility.createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: accessToken,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
signature = $cordovaOauthUtility.createSignature('POST', 'https://api.twitter.com/1.1/statuses/update.json', params, { status: "hello" }, CONFIG.TWITTER_CONSUMER_KEY_SECRET, accessTokenSecret);
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: "hello"
}, {
headers: {
Authorization: signature.authorization_header
}
})
.then(function (response) {
return response;
}).catch(function (error) {
console.log(error);
});
}
更新2
尝试了所有可能性后,问题仍然存在。这里我贴一个plnkr我的代码在哪里。
最佳答案
您正在使用加密的 HmacSHA256
,但发送 HMAC-SHA1
作为 oauth_signature_method
参数(即 Twitter 参数)。
您可能应该将代码更改为
oauth_signature = CryptoJS.HmacSHA1(signature_base_string, signing_key).toString(CryptoJS.enc.Base64);
如果您查看您的 authorization
header ,您还会发现其中存在问题。事实上,您可以看到 oauth_nonce
和 oauth_version
都以 &
符号为前缀,这不应该是这种情况,而且很可能意味着对于 api,您没有指定它们。这可能是因为您使用相同的 reqArray
来构造签名和 header ,或者您的代码未更新。
您可能也不想更改从应用程序发送的全局 header ,以防同时向另一个 api 发送另一个请求。相反,您应该仅为此特定 xhr 发送此 authorization
header 。
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: 'hello world',
}, {
headers: {
Authorization: auth,
},
})
关于javascript - 推特 REST API : Bad Authentication data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44157108/