0wn0r
0wn0r

Reputation: 11

Twitter OAuth with Android - Still getting a 401 but no glue where the mistake is located

I'm experiencing some problems regarding Twitter OAuth within an android activity. I read a lot of tutorials and example code, but I'm still not able to receive the access token.

Everytime I try to authorize I'm getting this OAuthNotAuthorizedException:

oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.

I googled a lot and it felt like I read thousands of solutions, but none of them worked out for me. Hope you can help me with this one (and I'm not bothering your with the same old newbie question! ;) )

Here is my complete activity code:

package de.ownor.moremote;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MakeTweet extends Activity {
    public static final String CONSUMER_KEY = "Y0iYMkUgNX8kKgvDjzFgg";
    public static final String CONSUMER_SECRET = "nuBZd8UGml5cjbm94Hf6dWOwIByrisZWpSnqODaUB5Q";
    public static final String CALLBACK_URL = "de.ownor.moremote://twitter";
    private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    private static final String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
    private static final String AUTH_URL = "https://api.twitter.com/oauth/authorize";
    public static final String PREFS_NAME = "TwitterLogin";
    public static final String TAG = "moremote - MakeTweet";

    private Twitter twitter;
    private CommonsHttpOAuthProvider provider;
    private CommonsHttpOAuthConsumer consumer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.setProperty("http.keepAlive", "false");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.make_tweet);

        twitter = null;
        if (!checkForSavedLogin()) {
            askOAuth();
        }

        getConsumerProvider();
    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("RESUMING!!");
        if (this.getIntent() != null && this.getIntent().getData() != null) {
            Uri uri = this.getIntent().getData();
            if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
                String verifier = uri
                        .getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
                try {
                    // this will populate token and token_secret in consumer

                    // /////////////////////////////
                    // exception is thrown here! //
                    // /////////////////////////////
                    provider.retrieveAccessToken(consumer, verifier);

                    // Get Access Token and persist it
                    AccessToken a = new AccessToken(consumer.getToken(),
                            consumer.getTokenSecret());
                    storeAccessToken(a);

                    // initialize Twitter4J
                    twitter = new TwitterFactory().getInstance();
                    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                    twitter.setOAuthAccessToken(a);
                    ((ApplicationEx) getApplication()).twitter = twitter;

                } catch (Exception e) {
                    // Log.e(APP, e.getMessage());
                    e.printStackTrace();
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    }

    private void askOAuth() {
        try {
            consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
                    CONSUMER_SECRET);
            provider = new CommonsHttpOAuthProvider(REQUEST_URL,
                    ACCESS_TOKEN_URL, AUTH_URL);
            provider.setOAuth10a(true);
            String authUrl = provider.retrieveRequestToken(consumer,
                    CALLBACK_URL);
            Toast.makeText(this, "Please authorize this app!",
                    Toast.LENGTH_LONG).show();
            setConsumerProvider();
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (Exception e) {
            Log.e(TAG, "Error in askOAuth");
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private Boolean checkForSavedLogin() {
        // Get Access Token and persist it
        AccessToken a = getAccessToken();
        if (a == null) {
            Log.d(TAG, "No saved Login found");
            return false;
        }

        // initialize Twitter4J
        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);
        ((ApplicationEx) getApplication()).twitter = twitter;

        return true;
    }

    private AccessToken getAccessToken() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME,
                MODE_PRIVATE);
        String token = settings.getString("accessTokenToken", "");
        String tokenSecret = settings.getString("accessTokenSecret", "");
        if (token != null && tokenSecret != null && !"".equals(tokenSecret)
                && !"".equals(token)) {
            return new AccessToken(token, tokenSecret);
        }
        return null;
    }

    private void storeAccessToken(AccessToken a) {
        SharedPreferences settings = Preferences.getPreferences(this);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("accessTokenToken", a.getToken());
        editor.putString("accessTokenSecret", a.getTokenSecret());
        editor.commit();
    }

    private void getConsumerProvider() {
        CommonsHttpOAuthProvider p = ((ApplicationEx) getApplication()).provider;
        if (p != null) {
            provider = p;
        }
        CommonsHttpOAuthConsumer c = ((ApplicationEx) getApplication()).consumer;
        if (c != null) {
            consumer = c;
        }
    }

    private void setConsumerProvider() {
        if (provider != null) {
            ((ApplicationEx) getApplication()).provider = provider;
        }
        if (consumer != null) {
            ((ApplicationEx) getApplication()).consumer = consumer;
        }
    }
}

The exception is thrown in the onResume()-Method. I marked the exact line. I really hope anyone can help me here. If you need further information just scream!

Thanks!

Simon.

Upvotes: 0

Views: 1571

Answers (2)

Zeus Monolitics
Zeus Monolitics

Reputation: 852

¿Are you using mHttpOauthprovider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize"); with HTTPS protocol?

Upvotes: 0

0wn0r
0wn0r

Reputation: 11

I finally managed to get the OAuth running. Unless I don't know the exact error. I guess it was some issue with the consumer.

Here is my running code:

onCreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.twitter);

    pref = Preferences.getPreferences(this);
    consumer = new CommonsHttpOAuthConsumer(Key.TW_CONSUMER_KEY,
            Key.TW_CONSUMER_SECRET);
    provider = new CommonsHttpOAuthProvider(Key.TW_REQUEST_TOKEN_URL,
            Key.TW_ACCESS_TOKEN_URL, Key.TW_AUTHORIZE_URL);
    provider.setOAuth10a(true);

    [...]

    if (getIntent().getData() == null) {
        checkForSavedLogin();
    }
}

onResume:

protected void onResume() {
    super.onResume();

    Uri uri = getIntent().getData();
    if (uri != null
            && Key.TW_CALLBACK_URI.getScheme().equals(uri.getScheme())) {
        String token = pref.getString(Key.TW_REQUEST_TOKEN, null);
        String secret = pref.getString(Key.TW_REQUEST_SECRET, null);
        try {
            if (!(token == null || secret == null)) {
                consumer.setTokenWithSecret(token, secret);
            }
            String otoken = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

            Assert.assertEquals(otoken, consumer.getToken());

            provider.retrieveAccessToken(consumer, verifier);
            token = consumer.getToken();
            secret = consumer.getTokenSecret();
            saveAuthInformation(token, secret);
            // Delete request information
            saveRequestInformation(null, null);

            if (!(token == null || secret == null)) {
                Log.d(TAG, "Twitter login found!");
                consumer.setTokenWithSecret(token, secret);
                twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(Key.TW_CONSUMER_KEY,
                        Key.TW_CONSUMER_SECRET);
                twitter.setOAuthAccessToken(new AccessToken(token, secret));
            }
        } catch (Exception e) {
            Log.d(TAG, "Couldn't receive token" + e.getMessage());
            e.printStackTrace();
        }
    }

    [...]
}

other methods:

private void checkForSavedLogin() {
    if (pref.contains(Key.TW_USER_TOKEN)
            && pref.contains(Key.TW_USER_SECRET)) {
        token = pref.getString(Key.TW_USER_TOKEN, null);
        secret = pref.getString(Key.TW_USER_SECRET, null);
        if (!(token == null || secret == null)) {
            Log.d(TAG, "Twitter login found!");
            consumer.setTokenWithSecret(token, secret);
            twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(Key.TW_CONSUMER_KEY,
                    Key.TW_CONSUMER_SECRET);
            twitter.setOAuthAccessToken(new AccessToken(token, secret));
        }
    } else {
        Log.d(TAG, "No Twitter login saved - asking for OAuth");
        askOAuth();
    }
}

private void askOAuth() {
    try {
        String authUrl = provider.retrieveRequestToken(consumer,
                Key.TW_CALLBACK_URI.toString());
        saveRequestInformation(consumer.getToken(),
                consumer.getTokenSecret());
        Toast.makeText(this, "Please authorize this app!",
                Toast.LENGTH_LONG).show();
        this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                .parse(authUrl)));
    } catch (OAuthException e) {
        e.printStackTrace();
    }
}

private void saveRequestInformation(String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = pref.edit();
    if (token == null) {
        editor.remove(Key.TW_REQUEST_TOKEN);
    } else {
        editor.putString(Key.TW_REQUEST_TOKEN, token);
    }

    if (secret == null) {
        editor.remove(Key.TW_REQUEST_SECRET);
    } else {
        editor.putString(Key.TW_REQUEST_SECRET, secret);
    }

    editor.commit();
}

private void saveAuthInformation(String token, String secret) {
    pref = Preferences.getPreferences(this);
    Editor editor = pref.edit();
    editor.putString(Key.TW_USER_TOKEN, token);
    editor.putString(Key.TW_USER_SECRET, secret);
    editor.commit();
}

Feel free to use this code... :)

Upvotes: 1

Related Questions