为什么Twitter API授权数据可以通过GET或POST参数而不是HTTP标头发送?

时间:2013-03-05 10:40:19

标签: ajax oauth http-headers twitter

我在Greasemonkey脚本中使用oauth.js和sha1.js:

// ==UserScript==
// @name        twitter_api
// @namespace   twitter
// @include     *
// @version     1
// @require http://oauth.googlecode.com/svn/code/javascript/oauth.js
// @require http://pajhome.org.uk/crypt/md5/sha1.js
// ==/UserScript==

var url = "https://api.twitter.com/1.1/statuses/update.json";
var accessor = {
  token: "XXX",
  tokenSecret: "XXX",
  consumerKey : "XXX",
  consumerSecret: "XXX"
};
var message = {
  action: url,
  method: "POST",
  parameters: {status: "apitest"}
};
OAuth.completeRequest(message, accessor);
OAuth.SignatureMethod.sign(message, accessor);
var authorization = "OAuth oauth_consumer_key=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_consumer_key) + "\""
            + ", oauth_nonce=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_nonce) + "\""
            + ", oauth_signature=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_signature) + "\""
            + ", oauth_signature_method=\"HMAC-SHA1\""
            + ", oauth_timestamp=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_timestamp) + "\""
            + ", oauth_token=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_token) + "\""
            + ", oauth_version=\"1.0\"";

在POST请求中使用Authorization标头:

GM_xmlhttpRequest({
  method: "POST",
  url: url,
  data: "status=apitest",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": authorization
  },
  onload: function(response) {
    alert(response.responseText);
  }
});

仅在POST请求中使用GET参数:

GM_xmlhttpRequest({
  method: "POST",
  url: url + '?' + OAuth.formEncode(message.parameters),
  onload: function(response) {
    alert(response.responseText);
  }
});

仅对POST请求使用POST参数:

GM_xmlhttpRequest({
  method: "POST",
  url: url,
  data: OAuth.formEncode(message.parameters),
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  onload: function(response) {
    alert(response.responseText);
  }
});

为什么当Twitter明确表示你必须发送授权标题时,这3个AJAX请求是否有效? https://dev.twitter.com/docs/auth/authorizing-request

如果同时接受GET,POST,HTTP标头授权,为什么我更喜欢HTTP标头,它是否更安全,或者它无关紧要,因为它是一个API调用?

0 个答案:

没有答案