2
votes

I am writing a code for oauth with twitter, and i have 401 error code and "Failed to validate oauth signature and token" response from twitter when i fetch post request to https://api.twitter.com/oauth/request_token. This is my data which i have:

Consumer/api key    - ffo9MLdRF8XOd9DKB0HeA
Consumer/api secret - fUJtvIpujTslQOlVbZY6QU8cNEMdwoxzTG1gh93SUgs
Url callback        - https://oauth.vk.com/blank.html

My steps:

1.Prepared string for making signature

POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttps%3A%2F%2Foauth.vk.com%2Fblank.html%26oauth_consumer_key%3Dffo9MLdRF8XOd9DKB0HeA%26oauth_nonce%3Dfb0e9383f0c84326a124dd4ccfddd2d2%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1393951866%26oauth_version%3D1.0

2.Created signature qQwIvFao9yeIQpi9ouz0oFi7/v8= by code:

public String calculateSign(String stringToEncode, String secret) throws Exception{
    byte[] keyBytes = secret.getBytes();
    byte[] text = stringToEncode.getBytes();

    SecretKey secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKey);

    byte[] encoded = mac.doFinal(text);
    return new String(Base64.encode(encoded, Base64.DEFAULT)).trim();
}

3.Final Authorization header (with escaped quotes):

OAuth oauth_nonce="fb0e9383f0c84326a124dd4ccfddd2d2", oauth_callback="https%3A%2F%2Foauth.vk.com%2Fblank.html", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1393951866", oauth_consumer_key="ffo9MLdRF8XOd9DKB0HeA", oauth_signature="qQwIvFao9yeIQpi9ouz0oFi7%2Fv8%3D", oauth_version="1.0"

Question to people who maybe knows how to work with twitter. What is wrong with my data? I can provide more code, but i think it is not useful.

P.S. - i provided working credentials, i will change them after 3 - 4 hours.

UPD: This is my key which used in calculateSign function

fUJtvIpujTslQOlVbZY6QU8cNEMdwoxzTG1gh93SUgs%26
1
There might be difference between the your machine and server timestamp. Although, I did it 1.5 years back but remember facing such issue. Twitter authentication fails if time difference between server and client is more that 1 hour.jsjunkie
Whou, is it possible to learn time of server for test?Vetalll
Please check the points mentioned here dev.twitter.com/discussions/204jsjunkie

1 Answers

1
votes

There is an error in your signature base string. The callback url should be double encoded so it should be:

... &oauth_callback%3Dhttps%253A%252F%252Foauth.vk.com%252Fblank.html ...

Also you do not need to percent encode the ampersand ('&') character in the signing key, so you should use:

fUJtvIpujTslQOlVbZY6QU8cNEMdwoxzTG1gh93SUgs&

You can check your signature using the online OAuth Test Console.