Oleksandr
Oleksandr

Reputation: 3764

401 Failed to validate oauth signature and token (https://api.twitter.com/oauth/request_token) (Java code)

I try to get oauth_token from twitter api but get exception:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.twitter.com/oauth/request_token

Error stream get:
Failed to validate oauth signature and token

Here is a signatureBaseString, signature and Authorization header example :
signatureBaseString: POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252F127.0.0.1%253A8080%252Ftwlogin%26oauth_consumer_key%3D2YhNLyum1VY10UrWBMqBnatiT%26oauth_nonce%3D1413642155863%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1413642155%26oauth_version%3D1.0

oAuthSignature: +Ov4WEws5XULVIxx9n/Q9ybzlrM=

authorizationHeaderValue: OAuth oauth_callback="http%3A%2F%2F127.0.0.1%3A8080%2Ftwlogin", oauth_consumer_key="2YhNLyum1VY10UrWBMqBnatiT", oauth_nonce="1413642155863", oauth_signature="%2BOv4WEws5XULVIxx9n%2FQ9ybzlrM%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1413642155", oauth_version="1.0"

Here is a code:
NameValuePair comparator:

class NvpComparator implements Comparator<NameValuePair> {
        @Override
        public int compare(NameValuePair arg0, NameValuePair arg1) {
            String name0 = arg0.getName();
            String name1 = arg1.getName();
            return name0.compareTo(name1);
        }
    }

URL encode

class OAuth{
...
    public static String percentEncode(String s) {
            return URLEncoder.encode(s, "UTF-8")
                    .replace("+", "%20").replace("*", "%2A")
                    .replace("%7E", "~");
    }
...
}

Request method

public String twAuth() {
            String method = "POST";
            String url = "https://api.twitter.com/oauth/request_token";
            String oAuthConsumerKey = "2YhNLyum1VY10UrWBMqBnatiT";
            String oAuthConsumerSecret = ***CONSUMER_SECRET***;
            String oAuthCallback = "http://127.0.0.1:8080/twlogin";
            String oAuthNonce = String.valueOf(System.currentTimeMillis());
            String oAuthSignatureMethod = "HMAC-SHA1";
            String oAuthTimestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String oAuthVersion = "1.0";

            List<NameValuePair> allParams = new ArrayList<NameValuePair>();
            allParams.add(new BasicNameValuePair("oauth_callback", oAuthCallback));
            allParams.add(new BasicNameValuePair("oauth_consumer_key", oAuthConsumerKey));
            allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
            allParams.add(new BasicNameValuePair("oauth_signature_method", oAuthSignatureMethod));
            allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
            allParams.add(new BasicNameValuePair("oauth_version", oAuthVersion));

            Collections.sort(allParams, new NvpComparator());

            StringBuffer params = new StringBuffer();
            for(int i=0;i<allParams.size();i++)
            {
                NameValuePair nvp = allParams.get(i);
                if (i>0) {
                    params.append("&");
                }
                params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
            }

            String signatureBaseStringTemplate = "%s&%s&%s";
            String signatureBaseString =  String.format(signatureBaseStringTemplate,
                    OAuth.percentEncode(method),
                    OAuth.percentEncode(url),
                    OAuth.percentEncode(params.toString()));

            String signatureKey = OAuth.percentEncode(oAuthConsumerSecret)+"&";

        SecretKeySpec signingKey = new SecretKeySpec(signatureKey.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(signatureBaseString.getBytes());
            String oAuthSignature = new String(Base64.encodeBase64(rawHmac));

        String authorizationHeaderValueTempl = "OAuth oauth_callback=\"%s\", " +
                    "oauth_consumer_key=\"%s\", " +
                    "oauth_nonce=\"%s\", " +
                    "oauth_signature=\"%s\", " +
                    "oauth_signature_method=\"%s\", " +
                    "oauth_timestamp=\"%s\", " +
                    "oauth_version=\"%s\"";

            String authorizationHeaderValue =String.format(authorizationHeaderValueTempl,
                    OAuth.percentEncode(oAuthCallback),
                    OAuth.percentEncode(oAuthConsumerKey),
                    OAuth.percentEncode(oAuthNonce),
                    OAuth.percentEncode(oAuthSignature),
                    OAuth.percentEncode(oAuthSignatureMethod),
                    OAuth.percentEncode(oAuthTimestamp),
                    OAuth.percentEncode(oAuthVersion));

        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", authorizationHeaderValue);

        con.setDoOutput(true);

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString());

        return "aboutas";
    }


Here is a twitter application settings:
Consumer Key (API Key): 2YhNLyum1VY10UrWBMqBnatiT
Callback URL: http://127.0.0.1:8080/twlogin
Sign in with Twitter: Yes
Website: http://127.0.0.1:8080

Can anybody help me? I don't know what to do..

Upvotes: 1

Views: 2040

Answers (1)

Oleksandr
Oleksandr

Reputation: 3764

I set false timestamp, because I have different time zone with Twitter servers.

This is code to set true oAuthTimestamp:

HttpsURLConnection con = (HttpsURLConnection)
                    new URL("https://api.twitter.com/oauth/request_token").openConnection();
            con.setRequestMethod("HEAD");
            con.getResponseCode();
            String twitterDate= con.getHeaderField("Date");
            DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
            Date date = formatter.parse(twitterDate);
            String oAuthTimestamp = String.valueOf(date.getTime()/1000L);

Upvotes: 1

Related Questions