Twitter, JavaScript & OAuth: failed to validate oauth signature and token - javascript

Im trying to implement OAuth using JavaScript, but when I make my request to http://api.twitter.com/oauth/request_token I am getting the above message in the response ("failed to validate oauth signature and token").
As far as I can tell I'm including all the correct parameters, both in the encoding of the signature base:
basestring: (consumer key removed for security)
POST&http%3A%2F%2Ftwitter.com%2Foauth%2Frequest_token%26oauth_callback
%3Doob%26oauth_consumer_key
%3D11111111111111111111112222222222222%26oauth_nonce
%3DO3cHsSXrfnzT%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp
%3D1275928008%26oauth_version%3D1.0
consumer secret: (removed for security)
11111111111111111111112222222222222&
Signature:
R3eHMuQ04F37+xPJSIsoo0aMzc8
Post Data: (consumer key removed for security)
oauth_callback=oob&oauth_consumer_key=11111111111111111111112222222222222&oauth_signature_method=HMAC-SHA1&oauth_signature=pjDh8jkp89ThBtzzB9dQmxQfcg&oauth_timestamp=1275928413&oauth_nonce=qyq3Jhn8rtTZ&oauth_version=1.0
And I've checked that the clock is correct on my device as that's the only real result I can find for this problem :( The nonce is unique and generated every time it runs...
Unfortunately I don't know where to look now. I can't spot anything obvious. I've re-written the entire request twice - once using the oauth.js library and once completely manually, but in both cases it fails with the same error!
Any suggestions?
Cheers

Perhaps the same as this question - which links to a discussin on twitter: apparently client side javascript with oob is not allowed!?!?

Your signature looks wrong, it should always end with a =. Here is an example of a valid one: "YEBbMFDYmp6DvZ3qW1aCx8q7kTc=". Your base string looks right, so I think you've made a mistake with your signature key.
In C#, here is how I built my signature key,
string signatureKey = Uri.EscapeDataString( consumer_secret ) + "&";
var hmacsha1 = new HMACSHA1( new ASCIIEncoding().GetBytes(signatureKey));
string signatureString = Convert.ToBase64String(
hmacsha1.ComputeHash(
new ASCIIEncoding().GetBytes( signatureBaseString ) ) );
string oauth_signature = signatureString;
More info on this process: https://www.dinochiesa.net/?p=17

Related

Verify Stripe web-hook manually

I am trying to manually verify web-hook:
const stripeSecret = createHmac('sha256', STRIPE_SIGNING_SECRET)
.update(event.body)
.digest('hex');
if(stripeSecret !== keyFromHeader) {
throw err();
}
But it is not matched with Stripe secret key which is received in header.
Here is event data which I am also trying to use in Stripe API (it also fails):
it's not event.body you should hash According to the documentation (https://stripe.com/docs/webhooks/signatures#verify-manually
) its a concatenation of :
The timestamp (as a string)
The character .
The actual JSON payload (i.e., the request body) => JSON.stringify(req.body)
you will need to parse this to get the timestamp (the xxxxx in the "t=xxxxx" part)
const sig = request.headers['stripe-signature'];
if you give me a sample stripe signature header i can try a code sample.
event.body might not be enough — it's very common in Node server environments for that to be a "parsed" version of the incoming request body, and instead you need to make sure to access the actual raw JSON string in the body — that's what Stripe's signature is computed against. It can be a little tricky!
https://github.com/stripe/stripe-node/tree/master/examples/webhook-signing
(and many examples contributed for various frameworks at https://github.com/stripe/stripe-node/issues/341 )
Also, is there a specific reason to do this manually and not just use Stripe's Node library? :)

I Call SmartContract Token ERC20, Why Show Hashing Output?

I do not know why with this, even though in the previous version (web3 + Metamask) can issue real data. But now used as hashing (output). I took the example in the code and output below (to get the TotalSupply on the ERC20 Token):
Output : 0x18160ddd
const contractInstance = web3.eth.contract(contractAbi).at(contractAddress);
const total_supply = contractInstance.totalSupply.getData();
console.log(total_supply);
How to showing real data? In a sense it doesn't come out hashing. Thanks
.getData() returns the ABI-encoded input you would have to send to the smart contract to invoke that method.
If you want to actually call the smart contract, use .call() instead.

Fail to verify RSA signature on server side that was created using Javascript on client side

I'm using forge on the client where I create the signature as follows.
//Client Side
var md = forge.md.sha256.create();
md.update(encryptedVote, 'utf8');
var pss = forge.pss.create({
md: forge.md.sha256.create(),
mgf: forge.mgf.mgf1.create(forge.md.sha256.create()),
saltLength: 20
});
var signature = privateKey.sign(md, pss);
Then later on the server I try to verify the signature using the cryptography library as follows.
#server side
user_public_key_loaded.verify(
signature,
enc_encrypted_vote,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=20
),
hashes.SHA256()
)
I get consistently an Invalid signature error. I tried changing the encoding on the client to md.update(encryptedVote, 'latin1'); and now sometimes works some others it doesn't.
Any idea what I'm doing wrong?
I found hy sometimes it worked an sometimes it didn't. before verifying I was putting the JSON data into a list by doing my_list = list(my_dict.values()). And accessing the signature and vote by doing my_list[0] and my_list[1]. Apparently the order of the data in the list is random and changes from time to time. Thus the signature and vote were switching place in my function and sometimes it worked some others it didn't.

javascript - make facebook page post

I am not using the Javascript SDK because that is client-side whereas I'm making a server-side call.
I want to make a page post so that I can make an ad creative with it. I can do the call perfectly fine in the Graph API Explorer tool, but I cannot make the same call (with the same long-lived access tokens that continue to work in the Graph Explorer) from Javascript. Here is my code:
tok = <valid and never expiring user token>;
var pg_tok = <valid and never expiring page token>;
var act_id = <account_id>;
var pg_id = <page_id>;
var call_to_action = 'INSTALL_MOBILE_APP';
var fb_app_url = 'https://itunes.apple.com/us/app/id284882215';
var msg = 'Test creative, ya see';
var pic_url = 'https://s3.amazonaws.com/<path_to_my_image>';
var ROOT = 'https://graph.facebook.com/';
var pagepost_endpoint = ROOT+pg_id+'/feed';
console.log(pagepost_endpoint);
var pagepost_params = {
access_token: pg_tok,
call_to_action: {
type: call_to_action,
value: {link: fb_app_url}
},
message: msg,
picture: pic_url,
published: false
};
console.log(pagepost_params);
var pagepost_res = HTTP.post(pagepost_endpoint, {params: pagepost_params});
console.log(pagepost_res);
I have played around a bunch with params vs. data for where pagepost_params goes in the HTTP.post that is giving the error (that is Meteor's HTTP btw).
-Putting everything in params gives the error: {"error":{"type":"Exception","message":"No Call To Action Type was parseable. Please refer to the call to action api documentation","code":1373054,"is_transient":false}}.
-Putting everything in data gives the error: {"error":{"message":"(#200) This API call requires a valid app_id.","type":"OAuthException","code":200}}.
-Putting access_token in params and everything else in data gives the error: {"error":{"message":"Invalid parameter","type":"FacebookApiException","code":100,"error_subcode":1349125}}.
One more clue for everyone, if I change the HTTP.post to HTTP.get, and just put access_token in params and include no other parameters (in params or in data), the call succeeds and I see past posts I have made on this page through the Graph Explorer (only the ones with published: true, though), so the access token and endpoint do work, just something is faulty about POST-ing instead of GET-ing and the specific parameters I'm using.
Have you tried posting to /photos instead of /feed? The error subcode is the same as mentioned here Posting to facebook wall using graph api
Hope this helps
Turned out to be an issue with Meteor's HTTP. It does not handle nested JSON very well, and we're going to submit a pull request for that. But for those seeing this, the important thing to take away is that the call_to_action may not be a valid JSON object, and even if it is, it may not be being stringified/parsed as expected. My fix was using request.post instead of HTTP.post. (then instead of params or data, you use form. look up node's request https://github.com/mikeal/request)

Struggling to build a JS/PHP validation function for my app

I have a web service that returns a JSON object when the web service is queried and a match is found, an example of a successful return is below:
{"terms":[{"term":{"termName":"Focus Puller","definition":"A focus puller or 1st assistant camera..."}}]}
If the query does not produce a match it returns:
Errant query: SELECT termName, definition FROM terms WHERE termID = xxx
Now, when I access this through my Win 8 Metro app I parson the JSON notation object using the following code to get a JS object:
var searchTerm = JSON.parse(Result.responseText)
I then have code that processes searchTerm and binds the returned values to the app page control. If I enter in a successful query that finds match in the DB everything works great.
What I can't work out is a way of validating a bad query. I want to test the value that is returned by var searchTerm = JSON.parse(Result.responseText) and continue doing what I'm doing now if it is a successful result, but then handle the result differently on failure. What check should I make to test this? I am happy to implement additional validation either in my app or in the web service, any advice is appreciated.
Thanks!
There are a couple of different ways to approach this.
One approach would be to utilize the HTTP response headers to relay information about the query (i.e. HTTP 200 status for a found record, 404 for a record that is not found, 400 for a bad request, etc.). You could then inspect the response code to determine what you need to do. The pro of this approach is that this would not require any change to the response message format. The con might be that you then have to modify the headers being returned. This is more typical of the approach used with true RESTful services.
Another approach might be to return success/error messaging as part of the structured JSON response. Such that your JSON might look like:
{
"result":"found",
"message":
{
"terms":[{"term":{"termName":"Focus Puller","definition":"A focus puller or 1st assistant camera..."}}]}
}
}
You could obviously change the value of result in the data to return an error and place the error message in message.
The pros here is that you don't have to worry about header modification, and that your returned data would always be parse-able via JSON.parse(). The con is that now you have extra verbosity in your response messaging.

Categories