Integrating Facebook Accounts

This topic explains how to allow your users to sign up for and log in to your mobile app with their Facebook account. Just add a few parameters in the developer portal and a few lines of code in your mobile app and you will be social-ready!

Configuring Facebook integration

Creating a Facebook application

To get started, you first need to create a Facebook application and get your Facebook app ID and app secret. For the detailed instructions, see the Facebook official documentation.

You need to provide the following information. In the "Valid OAuth redirect URIs," please specify the value that corresponds to the server location you've selected (please put your AppID in ${your-app-id}).

  • Display Name
  • Namespace
  • Category
  • Valid OAuth redirect URIs (After creating the application, add "Facebook Login" in the Production section and select the "Settings")
    • United States: https://${your-app-id}.us.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback
    • Japan: https://${your-app-id}.jp.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback
    • Singapore: https://${your-app-id}.sg.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback
    • Europe: https://${your-app-id}.eu.kiiapps.com/api/apps/${your-app-id}/integration/webauth/callback

Configuring a Kii application

Take the following steps in the developer portal to configure your application by setting your Facebook app ID and app secret.

  1. Click on the "Edit" button in your application console in the developer portal.

  2. Click "SOCIAL NETWORKS".

  3. Click "Facebook" to open the configuration screen for Facebook.

  4. Set your Facebook app ID and app secret.

Then, add the following tag under the application tag in your AndroidManifest.xml so as to enable the Activity that the SDK uses for Facebook authentication.

<activity
    android:name="com.kii.cloud.storage.social.connector.KiiSocialNetworkConnectorLoginActivity"
    android:label="@string/app_name" />

Logging in with a Facebook account

There are two ways to log in with a Facebook account.

The latter method (using the login UI) will be discontinued in near future. It is now outside of our support. Use the former method of using a Facebook access token.

Using a Facebook access token

The following example illustrates how to authenticate a user by using a Facebook access token.

// Create a KiiSocialConnect instance.
KiiSocialConnect connect = Kii.socialConnect(KiiSocialConnect.SocialNetwork.SOCIALNETWORK_CONNECTOR);

// Specify Facebook as the social network provider for logging in to Kii Cloud.
Bundle option = new Bundle();
option.putParcelable(KiiSocialNetworkConnector.PROVIDER, KiiSocialNetworkConnector.Provider.FACEBOOK);

// Set a Facebook access token.
option.putString(KiiSocialNetworkConnector.ACCESS_TOKEN, accessToken);

// Authenticate the user to Kii Cloud with the Facebook access token.
connect.logIn(null, option, new KiiSocialCallBack() {
  @Override
  public void onLoginCompleted(KiiSocialConnect.SocialNetwork network, KiiUser user, Exception exception) {
    if (exception != null) {
      // Handle the error.
      return;
    }
  }
});

The basic steps are as follows.

  1. Get a Facebook access token. For the detailed instructions, see Configuration and implementation example below. You can also see the Facebook official documentation.

  2. Create an instance of a social network connector with the socialConnect() method. The argument is KiiSocialConnect.SocialNetwork.SOCIALNETWORK_CONNECTOR.

  3. Create a Bundle instance and specify the target social network. Provider.FACEBOOK is specified here.

  4. Set the Facebook access token to the bundle.

  5. Authenticate the user with the logIn() method. If the specified account is new to Kii Cloud, the user is registered before the login. The logIn() method is non-blocking and receives the processing result with the callback method.

    When an access token is used for the login, all the processing is done in the background with no login screen for Facebook. You do not need to implement additional processing that are necessary when using the login UI provided by the SDK. Specifically, you do not need to specify the first parameter Activity of the logIn() method nor add code to the onActivityResult() method.

If the login is successful, the user is cached inside the SDK as the current user and you can get the user information with the getCurrentUser() method. You can also retrieve the access token and related parameters with the getAccessTokenBundle() method as follows:

// Get the token bundle for the social network provider.
KiiSocialConnect connect = Kii.socialConnect(SocialNetwork.SOCIALNETWORK_CONNECTOR);
Bundle b = connect.getAccessTokenBundle();

// Get the access token.
String accessToken = b.getString("oauth_token");

// Get the user ID provided by the social network provider.
String providerUserId = b.getString("provider_user_id");

// Check if a new Kii user was created when the logIn() method was executed.
boolean kiiNewUser = b.getBoolean("kii_new_user");

Using the login UI provided by the SDK (Deprecated)

Here is the sample code for letting a new user log in with their Facebook account:

Activity activity = this.getActivity();
KiiSocialConnect connect = Kii.socialConnect(SocialNetwork.SOCIALNETWORK_CONNECTOR);

Bundle options = new Bundle();
options.putParcelable(KiiSocialNetworkConnector.PROVIDER, KiiSocialNetworkConnector.Provider.FACEBOOK);

// Login.
connect.logIn(activity, options, new KiiSocialCallBack() {
  @Override
  public void onLoginCompleted(SocialNetwork network, KiiUser user, Exception exception) {
    if (exception != null) {
      // Handle the error.
      return;
    }
  }
});

The basic steps are as follows.

  1. Create an Activity for handling logging in with a Facebook account.
  2. Create a social network connector instance with the socialConnect() method. Here, we are specifying SocialNetwork.SOCIALNETWORK_CONNECTOR.
  3. Create a bundle and specify the target social network service. In this case, we are specifying Provider.FACEBOOK.
  4. Authenticate the user with the logIn() method. If the specified Facebook account is new to Kii Cloud, the user is registered before the login. The logIn() method is non-blocking and receives the processing result with the callback method.

Note: You also need to add a method to the onActivityResult() method to finish the Facebook authentication.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == KiiSocialNetworkConnector.REQUEST_CODE) {
    Kii.socialConnect(SocialNetwork.SOCIALNETWORK_CONNECTOR).respondAuthOnActivityResult(
      requestCode,
      resultCode,
      data);
  }
}

Linking a Kii account to a Facebook account

You can link existing Kii users to their Facebook accounts. Linked users can log in to Kii Cloud via the Facebook authentication.

Here is the sample code for linking a Kii account to a Facebook account.

// Assume that a user has logged in.

// Create a KiiSocialConnect instance.
KiiSocialConnect connect = Kii.socialConnect(KiiSocialConnect.SocialNetwork.SOCIALNETWORK_CONNECTOR);

// Specify Facebook as the social network provider for logging in to Kii Cloud.
Bundle option = new Bundle();
option.putParcelable(KiiSocialNetworkConnector.PROVIDER, KiiSocialNetworkConnector.Provider.FACEBOOK);

// Set a Facebook access token.
option.putString(KiiSocialNetworkConnector.ACCESS_TOKEN, accessToken);

// Link the Facebook account with the currently logged-in Kii user.
connect.link(null, option, new KiiSocialCallBack() {
  @Override
  public void onLinkCompleted(KiiSocialConnect.SocialNetwork network, KiiUser user, Exception exception) {
    if (exception != null) {
      // Handle the error.
      return;
    }
  }
});

The basic steps are as follows.

  1. Create an instance of a social network connector with the socialConnect() method. The argument is KiiSocialConnect.SocialNetwork.SOCIALNETWORK_CONNECTOR.

  2. Create a Bundle instance and specify the target social network. Provider.FACEBOOK is specified here.

  3. Set a Facebook access token to the bundle. For getting a Facebook access token, see Configuration and implementation example below. You can also see the Facebook official documentation.

  4. Link the currently logged-in user with the Facebook account with the link() method. This method is non-blocking and receives the processing result in the callback method.

Unlinking a Kii account from a Facebook account

Here is the sample code for unlinking a Kii account from a Facebook account.

// Assume that a user has logged in.

// Create a KiiSocialConnect instance.
KiiSocialConnect connect = Kii.socialConnect(KiiSocialConnect.SocialNetwork.SOCIALNETWORK_CONNECTOR);

// Specify Facebook as the social network provider for logging in to Kii Cloud.
Bundle option = new Bundle();
option.putParcelable(KiiSocialNetworkConnector.PROVIDER, KiiSocialNetworkConnector.Provider.FACEBOOK);

// Unlink the Facebook account from the currently logged-in Kii user.
connect.unlink(null, option, new KiiSocialCallBack() {
  @Override
  public void onUnLinkCompleted(KiiSocialConnect.SocialNetwork network, KiiUser user, Exception exception) {
    if (exception != null) {
      // Handle the error.
      return;
    }
  }
});

The basic steps are as follows.

  1. Create an instance of a social network connector with the socialConnect() method. The argument is KiiSocialConnect.SocialNetwork.SOCIALNETWORK_CONNECTOR.

  2. Create a Bundle instance and specify the target social network. Provider.FACEBOOK is specified here.

  3. Unlink the currently logged-in user from the Facebook account with the unlink() method. This method is non-blocking and receives the processing result in the callback method.

Configuration and implementation example

This section briefly covers the steps for integrating Facebook account.

Getting a Facebook access token is out of the scope of Kii Cloud feature, so the steps covered in this section are just for your reference. These steps confirmed to work as of October 2017. Search general technical information on the Internet for the up-to-date and more detailed steps.

By following the steps below, you will be able to add a Facebook login button on your mobile app and to authenticate a user with his Facebook username and password. Once the user authentication is passed, your mobile app will get the user's Facebook access token. You can then use the token for leveraging Kii Cloud login and user linking functions, which are covered in the previous section of this page.

When checking articles on the Internet, be careful that some of them cover procedures for getting your (i.e., developer's) access token for auto-posting and such. For the integration with the Kii Cloud, you need to get an end user's access token.

Configuration on Facebook admin screen

The configuration is made in "facebook for developers".

  1. Open facebook for developers on your web browser and login.

  2. Select "Add a New App", or select the existing Facebook app.

  3. Run the Android "Quickstart".

    If you have not selected Android as the platform yet, start the Facebook SDK quickstart on the "Dashboard" screen by clicking the "Choose Platform" button and select "Android" as the platform.

    If you have already selected Android as the platform, select "Settings" - "Basic" and click the "Quick Start" button in the "Android" section.

  4. Follow the instructions in the quickstart and make the following configurations.

    • Check the API level set in the AndroidManifest.xml.
    • Set repositories and compile in the build.gradle that locate under the app or mobile directory.
    • Add facebook_app_id in the string resource.
    • Add the <meta-data> element in the AndrodiManifest.xml.
    • Set the package name and key hashes on the Facebook admin screen.

    You should be able to configure the settings just by following the instructions on the screen. If you failed, please check the following tips:

    • If you get an error when you try to sync the Android Studio after modifying the build.gradle, check the SdkVersion and the versions of the support libraries.
    • If you get an error with the keytool's -exportcert option when you try to set the key hashes, replace the option with the -export.
    • We recommend you to check if the keytool command works fine before you actually set the result of the command line to Facebook. You can do this by removing all commands after the pipe | that connects the keytool and openssl commands. The BASE64 string is sometimes generated even if the keytool command is throwing an error. Be careful with the Windows environment since the environment variable %HOMEPATH% does not contain any drive letter; if the working drive is different, you will get a wrong BASE64 string.
  5. You will get the Facebook App ID and App Secret. Set them in the developer portal.

Program implementation

After making the configuration on the dashboard screen, add the following implementations in your mobile app:

  1. Add a Facebook login button in a screen resource for the user authentication.

    <com.facebook.login.widget.LoginButton
              android:id="@+id/facebook_login_button"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content" />
    

    Adjust the layout to match with your mobile app's preference.

    The Facebook SDK will handle the process for getting user input and authenticating the user with this button.

  2. Add the procedures in an implementation class of the user authentication screen.

    Add the following fields in the class.

    private LoginButton mFacebookLoginButton;
    private CallbackManager mFacebookCallbackManager;
    

    Set a callback with the onCreate() method. Also, add the procedures for the situation in which a user is already logged in.

    if (AccessToken.getCurrentAccessToken() == null) {
      mFacebookCallbackManager = CallbackManager.Factory.create();
      mFacebookLoginButton = (LoginButton) findViewById(R.id.facebook_login_button);
      mFacebookLoginButton.registerCallback(mFacebookCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
          String accessToken = loginResult.getAccessToken().getToken();
          // Add Kii Cloud login process here.
        }
    
        @Override
        public void onCancel() {
        }
    
        @Override
        public void onError(FacebookException exception) {
        }
      });
    } else {
      String accessToken = AccessToken.getCurrentAccessToken().getToken();
      // Add Kii Cloud login process here.
    }
    

    You will add the processes for handling Kii Cloud login and user linking in two places where the comment // Add Kii Cloud login process here. is set. You can use the Facebook access token accessToken in the processes.

    In the latest SDK, the SDK will automatically execute the initialization code of the Facebook SDK FacebookSdk.sdkInitialize(), so you do not need to execute the method.

  3. Implement the onActivityResult() method.

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      mFacebookCallbackManager.onActivityResult(requestCode, resultCode, data);
    }
    

When you are done with the implementation, run your mobile app. A Facebook login button should appear on the screen where you have put the button.

The above sample only implements the basic feature for leveraging the access token. See the Facebook document for a complete implementation guide.