aleclarson
aleclarson

Reputation: 19055

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

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.

Upvotes: 1

Views: 679

Answers (1)

aleclarson
aleclarson

Reputation: 19055

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');
};

Upvotes: 1

Related Questions