How to “Sign in with Twitter” using twitter4j

Nice weather today in bay area!

After reading “http://twitter4j.org/en/code-examples.html#signinwithtwitter” and “http://nullinfo.wordpress.com/oauth-twitter/“, I would like to try it out by myself.

twitter4j is a well-supported and handy wrapper to use twitter API in Java world. There are also a lot of articles and tutorials about oauth support in twitter. Here is a step-by-step guide to write a simple “sign in with twitter” using twitter4j for dummy. :)

Assume you are a developer, and your twitter app would provide “sign in with twitter” to users.

Example One: your twitter app is a “desktop client” app.

Step 1: Register your twitter app: https://dev.twitter.com/apps

 
Fill out the application form:

Fill out those fields in the above form, remember to select “Client” as “Application Type”, and “Read and Write” as “Default Access Type”. You will be asked to agree upon the “Twitter API terms of service” after that.

Step 2: get your twitter app’s “Consumer key” and “Consumer Secret”:
After successfully register your new twitter app, you will be directed to your app’s setting page: (you can always check your app’s setting from “Your Apps” afterwards):

Consumer Key” and “Consumer Secret” will be used later in our example.

Step 3: our java code which will post a new tweet to user’s twitter account.
First let’s look at the source code, and then screenshots about execution result:


import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.conf.Configuration;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
import twitter4j.media.MediaProvider;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public final class loginTest {

    public static void main(String[] args) {
       
    	String testStatus="Hello from twitter4j";

    	ConfigurationBuilder cb = new ConfigurationBuilder();
    	
    	
    	//the following is set without accesstoken- desktop client
    	cb.setDebugEnabled(true)
  	  .setOAuthConsumerKey("YOUR_CONSUMER_KEY_HERE")
  	  .setOAuthConsumerSecret("YOUR_CONSUMER_SECRET_HERE");
  
        try {
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();
            
            try {
            	System.out.println("-----");

                // get request token.
                // this will throw IllegalStateException if access token is already available
                // this is oob, desktop client version
                RequestToken requestToken = twitter.getOAuthRequestToken(); 

                System.out.println("Got request token.");
                System.out.println("Request token: " + requestToken.getToken());
                System.out.println("Request token secret: " + requestToken.getTokenSecret());

                System.out.println("|-----");

                AccessToken accessToken = null;

                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                
                while (null == accessToken) {
                    System.out.println("Open the following URL and grant access to your account:");
                    System.out.println(requestToken.getAuthorizationURL());
                    System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
                    String pin = br.readLine();
               
                    try {
                        if (pin.length() > 0) {
                            accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                        } else {
                            accessToken = twitter.getOAuthAccessToken(requestToken);
                        }
                    } catch (TwitterException te) {
                        if (401 == te.getStatusCode()) {
                            System.out.println("Unable to get the access token.");
                        } else {
                            te.printStackTrace();
                        }
                    }
                }
                System.out.println("Got access token.");
                System.out.println("Access token: " + accessToken.getToken());
                System.out.println("Access token secret: " + accessToken.getTokenSecret());
                
            } catch (IllegalStateException ie) {
                // access token is already available, or consumer key/secret is not set.
                if (!twitter.getAuthorization().isEnabled()) {
                    System.out.println("OAuth consumer key/secret is not set.");
                    System.exit(-1);
                }
            }
            
           Status status = twitter.updateStatus(testStatus);

           System.out.println("Successfully updated the status to [" + status.getText() + "].");

           System.out.println("ready exit");
            
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            System.exit(-1);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println("Failed to read the system input.");
            System.exit(-1);
        }
    }
}

Step 4: execution:
The following is the console output ( I used Eclipse to run this java application ):

-----
Got request token.
Request token: G----------------------------------------0
Request token secret: 2-----------------------------------------I
|-----
Open the following URL and grant access to your account:

https://api.twitter.com/oauth/authorize?oauth_token=G----------------------------------------0

Enter the PIN(if available) and hit enter after you granted access.[PIN]:

After a closer look at the output, you will notice that the value of "oauth_token" in the url is the same as "Request token". Here I have masked the output, basically it is a random string.

Step 5: Get the PIN:
Copy and paste the above url in the console output to your browser.

If user have *NOT* logged in twitter, the user will see the following page ( enter username and password to twitter):

If user have *already* logged in twitter, the user will see the following page ( ask for permission ):

No matter what is the case, after user enter his username and password correctly, or click "authorize app", a webpage showing a "PIN" number is displayed:

Step 6: enter the PIN and post the tweet
Let's go back to the console output in "Step 4" (hope you have not closed that yet!), and enter the "PIN" number from the previous step.

The following is the complete console output (just an example, the value of 'request token):

-----
Got request token.
Request token: G----------------------------------------0
Request token secret: 2-----------------------------------------I
|-----
Open the following URL and grant access to your account:

https://api.twitter.com/oauth/authorize?oauth_token=G----------------------------------------0

Enter the PIN(if available) and hit enter after you granted access.[PIN]:4822813
Got access token.
Access token: 353205840-2vY4h7o8j50i0A4bzdsRhpcvFzOqskvWQKJtmVba
Access token secret: xo3f7MngeUBJIgb5e8S0PKR31LlhJYABlpe5XmnKJB
Successfully updated the status to [Hello from twitter4j].

Step 7: Verification
Based on the console output, we know the application has successfully completed the authorization for 'sign in with twitter' and also posted a new tweet "Hello from twitter4j" to user's twitter account. It is very easy to verify this. Simply go to the user's twitter web page and check the newest status there !

About these ads

About xmeng

an engineer currently living in bay area.
This entry was posted in App Development and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s