Phillip Schmidt
Phillip Schmidt

Reputation: 8818

Twitter Authentication with REST API

I'm getting a response back with body "unable to validate oauth signature and token" when trying to get the request token.

Here's the code I'm using to set up all the request parameters. I noted some places of interest that I think could possibly be the problem with a bunch of asterisks.

var appId = "myId"
  , appSecret = "mySecret"
  , redirectUrl = "http://localhost:8077/twitterLogin";

var d = new Date();
  , time = Math.floor(d.getTime() / 1000); //seconds since epoch

var oauth_nonce = Math.random() * 1000000; //************could be the issue, maybe?
  , oauth_callback = encodeURIComponent('http://localhost:8077/twitterLogin');

//****************more likely the issue
var paramString = encodeURIComponent('oauth_consumer_key=**MY_APP_ID**&oauth_callback='+ oauth_callback 
                                      + '&oauth_nonce=' + oauth_nonce 
                                      + '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + time 
                                      + '&=oauth_version=1.0');
var baseString = "POST&" + encodeURIComponent("https://api.twitter.com/oauth/request_token") + '&' + paramString; 

var signingKey = encodeURIComponent(appSecret) + '&' + encodeURIComponent(appSecret);
  , signature = crypto.createHmac('sha1', signingKey).update(baseString).digest('hex');

And here's the code for the request itself:

var requestBody = "oauth_callback="+ oauth_callback 
                + "&appId=" + appId
                + "&oauth_nonce=" + oauth_nonce 
                + "&oauth_signature=" + signature 
                + "&oauth_signature_method=HMAC-SHA1"
                + "&oauth_timestamp=" + time
                + "&oauth_version=1.0";
//*******also could be the issue. maybe missing headers or something?
request.post({url: 'https://api.twitter.com/oauth/request_token', body: requestBody}); 

I'm just wondering what I'm missing with the signature or the token..

Upvotes: 0

Views: 262

Answers (1)

Jon Susiak
Jon Susiak

Reputation: 4978

  • Firstly your parameters have to be sorted lexigraphically (alphabetically) before they are encoded, you need to switch the positions of oauth_callback and oauth_consumer_key.

  • Secondly, for an unauthorized request token, you calculate the signing key using your consumer secret appended with the '&' character. You have appended the secret a second time after the ampersand.

  • Thirdly in your request body you should use oauth_consumer instead of appId as the name of your parameter.

Try those fixes and see if it works.

Upvotes: 1

Related Questions