Master Facebook's OAuth process in Android


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 Android app access to their account. Our simple app simply logs users in and displays some info about their Facebook profile.

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. Go into Android Studio and select Open Project, and select the folder you've just unzipped.

3 Download the Temboo Android SDK and add it to the project as described in the Getting Started example. You'll need to add the core and Facebook .jar files.

4Confirm that your project has <uses-permission android:name="android.permission.INTERNET"/> in its manifest.

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/

6Go to the example code you downloaded earlier, and in FacebookOAuthHelper.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 FacebookOAuthHelper.java, substitute in your Temboo account details over the default values in the code. You can find these credentials on the Applications page of your Temboo account.

    // 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 Deploy and run the app. After a few moments you should be redirected to Facebook where you can log in and grant the application access. Once you've done so you should be redirected back to your application where you'll see your 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 WebView to display the Facebook login and grant-access screens. The FacebookOAuthHelper 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.
  • Below is how we generate the state token:

    // Generates a secure custom callback ID
    SecureRandom random = new SecureRandom();
    stateToken = "facebook-" + random.nextInt();
    

    After generating this token, we can execute the InitializeOAuth Choreo in the doInBackground method of the FacebookInitOAuthTask internal class. This is the point in the code where the user is redirected to Facebook in order to log in an grant the application access:

        private class FacebookInitOAuthTask extends AsyncTask<Void, Void, String> {
    
            @Override
            protected String doInBackground(Void... params) {
                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(FACEBOOK_APP_ID);
                    initializeOauthInputs.set_CustomCallbackID(stateToken);
                    initializeOauthInputs.set_ForwardingURL(forwardingURL);
    
                    // 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.
                    return initializeOauthResults.get_AuthorizationURL();
                } catch(Exception e) {
                    // if an exception occurred, log it
                    Log.e(this.getClass().toString(), e.getMessage());
                }
                return null;
            }
    
            protected void onPostExecute(String authURL) {
                try {
                    // Redirect the user to the authorization (Facebook) URL
                    webView.loadUrl(authURL);
                } catch(Exception e) {
                    // if an exception occurred, show an error message
                    Log.e(this.getClass().toString(), e.getMessage());
                }
            }
        }
    

    Note that we use the stateToken as the CustomCallbackID.

    Once the user logs in and authorizes the application, Facebook attempts to redirect the user to the forwarding URL specified in the initialize OAuth flow. Our WebView watches for this redirect, and when it identifies our forwarding URL as the target it prevents the redirect and instead uses Temboo to finalize the OAuth process. This is handled in our MainActivity class:

            // Set up WebView for OAuth2 login - intercept redirect when the redirect
            // URL matches our FORWARDING_URL, in which case we will complete the OAuth
            // flow using Temboo
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if(url.startsWith(FORWARDING_URL)) {
                        // spawn worker thread to do api calls to get list of contacts to display
                        oAuthHelper.getUserInfo();
                        // true = do not navigate to URL in web view
                        return true;
                    }
    
                    // Default behavior - redirect to specified URL
                    return super.shouldOverrideUrlLoading(view, url);
                }
            });
    

    The FacebookOAuthHelper class's getUserInfo method in turn runs the FinalizeOAuth choreo. Upon success of this choreo we can retrieve the Facebook access token. This functionality occurs in the FacebookFinalizeOAuth internal class:

        private class FacebookFinalizeOAuthTask extends AsyncTask<Void, Void, String> {
            @Override
            protected String doInBackground(Void... params) {
                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(FACEBOOK_APP_ID);
                    finalizeOauthInputs.set_AppSecret(FACEBOOK_APP_SECRET);
                    finalizeOauthInputs.set_LongLivedToken("1");
    
                    final String customCallbackID = TEMBOO_ACCOUNT_NAME + "/" + stateToken;
                    finalizeOauthInputs.set_CallbackID(customCallbackID);
    
                    // Execute FinalizeOAuth choreo and retrieve the access token
                    FinalizeOAuthResultSet finalizeOauthResults = finalizeOauthChoreo.execute(finalizeOauthInputs);
    
                    accessToken = finalizeOauthResults.get_AccessToken();
    
                    return "Retrieved access token: " + accessToken;
                } catch(Exception e) {
                    // if an exception occurred, log it
                    Log.e(this.getClass().toString(), e.getMessage());
                }
                return null;
            }
    
            protected void onPostExecute(String accessToken) {
                try {
                    new FacebookGetUserInfoTask().execute();
                } catch(Exception e) {
                    // if an exception occurred, show an error message
                    Log.e(this.getClass().toString(), e.getMessage());
                }
            }
        }
    

    The last step is to use the access token to retrieve the user's Facebook account information and write it into the WebView, which is done in the FacebookGetUserInfoTask internal class:

        private class FacebookGetUserInfoTask extends AsyncTask<Void, Void, String> {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    // 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(accessToken);
    
                    // Execute Facebook.Reading.User choreo.
                    UserResultSet userResults = userChoreo.execute(userInputs);
    
                    return userResults.get_Response();
                } catch(Exception e) {
                    // if an exception occurred, log it
                    Log.e(this.getClass().toString(), e.getMessage());
                }
                return null;
            }
    
            protected void onPostExecute(String userInfo) {
                try {
                    // Display user's account info
                    webView.loadData(userInfo, "text/json", "utf-8");
                } catch(Exception e) {
                    // if an exception occurred, show an error message
                    Log.e(this.getClass().toString(), e.getMessage());
                }
            }
        }
    

    Kick off the OAuth process by adding new FacebookInitOAuthTask().execute(); to the end of your MainActivity's onCreate method.

    We're all finished! This Android 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