Master Facebook's OAuth process in Java


Here we'll show you how to go through the Facebook OAuth process, which lets any Facebook user log in to Facebook and grant your Java app access to their account. Our simple app simply logs users in and displays some info about their Facebook profile.

In order to follow this example, you'll need Java 1.6 (or later), Maven (for building the project), and a Java application server listening on localhost:8080.

Maven comes installed on Mac OS X for version 10.8 and earlier. If you have 10.9 or higher, you can install Maven using the Homebrew command below or download the binary for any platform from the Maven site.

brew install maven

Run our Facebook OAuth Example

1 Log in to Temboo. If you don't already have an account, you can register for free.

2 Download our Facebook OAuth example code and unzip it.

3 Download the Temboo Java SDK and put it in the folder that you created in the last step when you unzipped the example code. The Temboo JAR file should be named according to Maven conventions (e.g., temboo-sdk-1.0.0.jar).

4 In a terminal window, navigate to the example code folder and run this command to set up Maven with a 'lib' directory to include the Temboo SDK:

mvn install:install-file -Dfile=temboo-sdk-1.0.0.jar -DgroupId=temboo -DartifactId=temboo-sdk -Dversion=1.0.0 -Dpackaging=jar -DlocalRepositoryPath=lib -DcreateChecksum=true

5 Create a new Facebook app via the Facebook developer console using the Apps menu at the top of the page. Once you've created a new App, click the Settings tab on the left, select + Add Platform, and choose the Website option. Set up your Temboo callback URL by specifying the following URL as your Site URL:

https://ACCOUNT_NAME.temboolive.com/callback/

6 Go to the example code you downloaded earlier, and in FacebookAuthHelper.java, substitute in your Facebook app details over the default values shown below:

	// Provide your Facebook App ID and App Secret.
	private static final String APP_ID = "YOUR_FACEBOOK_APP_ID";
	private static final String APP_SECRET = "YOUR_FACEBOOK_APP_SECRET";

7 Now, still in FacebookAuthHelper.java, substitute in your Temboo account details over the default values in the code.

    // Replace with your Temboo credentials.
    private static final String TEMBOO_ACCOUNT_NAME = "ACCOUNT_NAME";
    private static final String TEMBOO_APP_KEY_NAME = "APP_NAME";
    private static final String TEMBOO_APP_KEY_VALUE = "APP_KEY";

8 Next, we'll build the project using the following Maven command, run from the example code root directory that contains the Maven pom.xml file:

mvn clean install

9 Deploy the .war file created in the new 'target' directory to the application server of your choice (e.g., JBoss, Jetty, Tomcat). This usually involves placing the .war file in a specific directory e.g., the webapps directory if you're using Tomcat, and restarting your application server.

10 Once you've deployed the app, browse to the following URL:

http://localhost:8080/FacebookOAuthv1/

11 Click Facebook Login button and go through the OAuth process.

12 Once you've been redirected to Facebook, you can log in and grant the application access At this point in the example, you should be redirected back to your application where you'll see the user profile information in JSON format. That's it!

Taking a closer look at the code

This example includes an OAuth helper class for Facebook and a simple JSP page for initializing the OAuth flow and displaying user information. The FacebookAuthHelper.java class has a few components:

First, we generate a secure random state token and create a Temboo session object. Creating a state token can be handy in a couple ways:

  • When beginning the OAuth process, the InitializeOAuth Choreo will always return a CallbackID used to retrieve OAuth callback data after the user redirects back to your app's page. In some cases, it can be desirable to be able to predict this CallbackID by generating a state token and passing it as the CustomCallbackID in the InitializeOAuth Choreo and as part of the URL you provide for the ForwardingURL.
  • Your application can use the state token to finish the OAuth process and retrieve the user's access token.
  • Your application may also want to use a state token to detect the OAuth redirect or as part of the user session code, which is what we're demonstrating in this example.
  • Below is the method for generating the state token as well as an accessor method used to retrieve it:

    	/**
    	 * Generates a secure custom callback ID. This is used as the CustomCallbackID and sent 
    	 * as the state parameter in the ForwardingURL when the user is redirected back
    	 * to http://localhost:8080/FacebookOAuthv1/index.jsp.
    	 */
    	private void generateStateToken(){
    		SecureRandom random = new SecureRandom();
    		stateToken = "facebook-"+random.nextInt();
    	}
    	
    	/**
    	 * Accessor for state token.
    	 */
    	public String getStateToken(){
    		return stateToken;
    	}
    

    After generating this token, we can execute the InitializeOAuth Choreo in the getLoginUrl() method. This is the point in the code where the user is redirected to Facebook in order to log in an grant the application access:

    	/**
    	 * Executes Facebook.OAuth.InitializeOAuth in order to get an AuthorizationURL
    	 */
    	public String getLoginUrl() {
    
                String authURL = "";
                try {
                	// Instantiate the InitializeOAuth choreo, using a session object.
                    InitializeOAuth initializeOauthChoreo = new InitializeOAuth(session);
    
                    // Get an input set for InitializeOAuth.
                    InitializeOAuthInputSet initializeOauthInputs = initializeOauthChoreo.newInputSet();
               
               	// Set inputs for InitializeOAuth.
               	// Use a state token as the custom callback id and in a state parameter of the ForwardingURL.
                    initializeOauthInputs.set_AppID(APP_ID);
                    initializeOauthInputs.set_CustomCallbackID(stateToken);
                    initializeOauthInputs.set_ForwardingURL(FORWARDING_URL + "?state=" + stateToken);
    
                    // Execute InitializeOAuth choreo.
                    InitializeOAuthResultSet initializeOauthResults = initializeOauthChoreo.execute(initializeOauthInputs);
    
                    // This is the URL that the user will be directed to in order to login to FB and allow access.
                    authURL = initializeOauthResults.get_AuthorizationURL();
                    System.out.println("~~~AUTHORIZATION URL: " + authURL);
                } catch (Exception te) {
                    te.printStackTrace();
                }
                return authURL;
    	}
    

    Note that we use the stateToken as the CustomCallbackID and as a parameter in the ForwardingURL.

    The last step is to run the FinalizeOAuth Choreo and pass the returned access token to the Facebook > Reading > User Choreo to retrieve your user's profile information. The important thing to note here is that the stateToken is passed to this method from the page and used as the callback identifier in the FinalizeOAuth Choreo. This functionality occurs in the getUserInfo() method:

    	/**
    	 * Expects a state parameter which was passed as the CustomCallbackID and in the ForwardingURL
    	 * @return JSON response from Facebook.Reading.User choreo
    	 */
    	public String getUserInfo(final String state) throws IOException {
    
                	String userInfo = "";
                    try {
           		    // Instantiate the FinalizeOAuth choreo, using a session object.
                        FinalizeOAuth finalizeOauthChoreo = new FinalizeOAuth(session);
                        FinalizeOAuthInputSet finalizeOauthInputs = finalizeOauthChoreo.newInputSet();
                   
                   	    // Set input for FinalizeOAuth choreo.
                        finalizeOauthInputs.set_AppID(APP_ID);
                        finalizeOauthInputs.set_AppSecret(APP_SECRET);
                        finalizeOauthInputs.set_LongLivedToken("1");
    
                        final String customCallbackID = TEMBOO_ACCOUNT_NAME + "/" + state;
                        finalizeOauthInputs.set_CallbackID(customCallbackID);
    
                        // Execute FinalizeOAuth choreo.
                        System.out.println("~~~EXECUTING FINALIZE WITH CLIENT CALLBACK ID: " + customCallbackID);
                        FinalizeOAuthResultSet finalizeOauthResults = finalizeOauthChoreo.execute(finalizeOauthInputs);
                        System.out.println("~~~USER ACCESS TOKEN: " + finalizeOauthResults.get_AccessToken());
    
                        // Get user info. Instantiate the choreo, using a session object.
                        User userChoreo = new User(session);
    
                        // Get an InputSet object for the Facebook.Reading.User choreo.
                        UserInputSet userInputs = userChoreo.newInputSet();
    
                        // Pass access token to the Facebook.Reading.User choreo.
                        userInputs.set_AccessToken(finalizeOauthResults.get_AccessToken());
    
                        // Execute Facebook.Reading.User choreo.
                        UserResultSet userResults = userChoreo.execute(userInputs);
                        userInfo = userResults.get_Response();
                    } catch (Exception te) {
                        te.printStackTrace();
                    }
                    return userInfo;
    	}
    

    What's Next?

    We're all finished! This Java application executes the OAuth flow, and retrieves information about your app's user. We also have OAuth support for many other APIs in our Choreo Library.

    Once you've got your code up and running, you're ready to move on and do more. From monitoring your running applications, to moving your generated Temboo code to your preferred development environment and sharing it with colleagues, collaborators and friends - we've got you covered.

    Need help?

    We're always happy to help. Just email us at support@temboo.com, and we'll answer your questions.


    Back