2

我在 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\"";

将 Authorization 标头与 POST 请求一起使用:

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 明确表示您必须发送 Authorization 标头时,为什么这 3 个 AJAX 请求会起作用? https://dev.twitter.com/docs/auth/authorizing-request

如果 GET、POST、HTTP 标头授权都被接受,为什么我更喜欢 HTTP 标头,它更安全还是因为它是 API 调用而无关紧要?

4

0 回答 0