How to correctly sign an HTTP request to Twitter's REST API v1.1 in NodeJS?

别说谁变了你拦得住时间么 提交于 2020-01-06 03:55:06

问题


I'm only getting error 32 "Could not authenticate you" when I call twitter.request() (defined in my cloud/twitter.js file) inside Parse Cloud Code. I've done everything Twitter told me to do in "Creating a Signature" and "Authorizing a request" at dev.twitter.com, but I cannot seem to find how to do so.

Has anyone else had experience with accessing the Twitter REST API v1.1 using Parse Cloud Code?

P.S. You can assume I have the user's "access token" and "token secret" in a Parse.User as twitterToken and twitterTokenSecret, but I have also provided ACCESS_TOKEN and TOKEN_SECRET constants so you don't have to recreate my Parse.User to help me debug this.


回答1:


It turned out to be an easy fix (thankfully). The problem lied in a & trailing my signature (facepalm). Here's the function I had to change.

function getAuthSignature (user, request, oauth) {
  var signingKey, body, signatureBase;

  signingKey =
    ENCODING_METHOD(CONSUMER_SECRET) + '&' + ENCODING_METHOD(TOKEN_SECRET);

  body = 
    mapObject(oauth, ampersandEncoding)
    .concat(mapObject(request.params, ampersandEncoding))
    .sort();

  // Remove trailing ampersand. (aka the fix)
  body.push(body.pop().replace('&', ''));

  signatureBase =
    request.method.toUpperCase() + '&' +
    ENCODING_METHOD(request.url) + '&' +
    ENCODING_METHOD(body.join(''));

  return crypto.createHmac('sha1', signingKey)
               .update(signatureBase)
               .digest('base64');
};


来源:https://stackoverflow.com/questions/21654245/how-to-correctly-sign-an-http-request-to-twitters-rest-api-v1-1-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!