Facebook Login Authentication using FirebaseUI Auth

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Google Sign-In Authentication using FirebaseUI AuthTwitter Sign-In Authentication using FirebaseUI Auth


You are reading a sample chapter from the Firebase Essentials - Android Edition book.

Purchase the full edition of this book in eBook ($19.99) or Print ($38.99) format.
Firebase Essentials - Android Edition Print and eBook (ePub/PDF/Kindle) edition contains 55 chapters and 23 example apps. Learn more...

Buy eBook Buy Print Preview Book


So far in this book we have covered two different types of Firebase user authentication for Android apps. The first involved the creation of user accounts based solely on the user’s email address and a password. These accounts apply only to the Firebase project with which the Android app is associated and are unconnected to any accounts the user might have on other platforms.

The second approach, which was covered in the previous chapter, allows users to create an account and sign into Android apps based on existing Google account credentials. This has the advantage that the user does not have yet another login and password to keep track of along with those of other apps and web sites for which the user has signed up over the years.

This chapter will continue the theme of using third-party credentials to create an account and sign into the example FirebaseAuth app by making use of the Facebook Login provider.




Preparing the Project

As with the Google Sign-in example covered in the previous chapter, most of the steps required to configure the project to work with Facebook Login have already been performed in the chapter entitled Email/Password Authentication using FirebaseUI Auth. These steps include connecting the project to Firebase from within Android Studio and adding the build dependencies to the Gradle build files. A number of additional steps are, however, required in preparation for adding Facebook Login support to the project. These steps will be outlined in detail throughout the remainder of this chapter.

Obtaining the Facebook App ID and App Secret

The Facebook App ID and App Secret serve as the connection between the Android app and the Facebook Login service. Each app that makes use of Facebook developer services in any way must have a unique ID and secret, both of which are assigned by Facebook via the Facebook for Developers site.

To generate the ID and secret, begin by logging into the Facebook for Developers portal at the following URL:

https://developers.facebook.com/

Log into the developer portal using your Facebook account information (or create a Facebook account if you do not already have one) and, after signing in, navigate to the Facebook Login Apps page:

https://developers.facebook.com/apps/

On the apps page, click on the Add a New App button as highlighted in Figure 7-1:


Firebase auth facebook add app.png

Figure 7-1


In the resulting dialog fill in values for the Display Name, Contact Email and Category settings before clicking on the Create App ID button:


Firebase auth facebook new app id.png

Figure 7-2


If prompted, perform the security check task in the next dialog before clicking on the Submit button.

Once the app has been created, return to the Facebook apps screen and select the newly added app. From the left-hand navigation panel, select the Settings option. The app settings screen (Figure 7-3) will display a range of values, including the App ID and App Secret. If the App Secret is concealed, click on the Show button to reveal the value:


Firebase auth facebook app secret.png

Figure 7-3


Select the Advanced option in the navigation panel and enable the Native or desktop app? switch before clicking on the Save Changes button:


Firebase auth facebook native app.png

Figure 7-4


Adding the App ID and Secret to the Firebase Project

Open a second browser window and navigate to the Firebase console. Select the Firebase Examples project followed by the Authentication option. On the authentication screen, choose the Sign-In Method tab and click on the Facebook provider option. When the Facebook provider dialog appears (Figure 7-5) turn on the Enable switch and cut and paste the App ID and App Secret values from the Facebook for Developers app settings screen into the corresponding fields of the Firebase dialog:


Firebase auth facebook console enable.png

Figure 7-5


Copy the OAuth redirect URI shown at the bottom of the dialog in preparation for a later step, then click on the Save button to commit the settings and enable the Facebook provider.

Adding the Facebook Login Product to the App

Once a new app has been created, the Facebook products that are to be supported by the app need to be added. Within the Settings page, locate the Products section in the navigation panel and click on the + Add Product entry as illustrated in Figure 7-6:


Firebase auth facebook add product.png

Figure 7-6


When the Add Product link is clicked the Product Setup screen will appear containing a list of products that are available to be added to the app. Locate and click on the Get Started button next to the Facebook Login product and choose Android from the platform selection screen.

On the Android startup screen, click on the link that reads I already installed the SDK.

You are reading a sample chapter from the Firebase Essentials - Android Edition book.

Purchase the full edition of this book in eBook ($19.99) or Print ($38.99) format.
Firebase Essentials - Android Edition Print and eBook (ePub/PDF/Kindle) edition contains 55 chapters and 23 example apps. Learn more...

Buy eBook Buy Print Preview Book

Setting the OAuth Redirect URI

The OAuth Redirect URI copied from the Firebase console in a previous section now needs to be setup for the app within the Facebook for Developers portal. Select the Settings option listed under Facebook Login in the Products section of the navigation panel:


Firebase auth facebook login settings.png

Figure 7-7


On the settings screen, paste the Uri into the Valid OAuth redirect URIs field as shown in Figure 7-8 and turn on the Login from Devices option. Click on the Save Changes button before proceeding.


Firebase auth facebook oauth.png

Figure 7-8


Adding the Debug and Release Key Hash

The final task before modifying the code for the app is to add the debug release key for your Android development environment to the Facebook app configuration. This once again requires the use of the keytool utility together with the openssl tool. On macOS and Linux, open a terminal window and execute the following command to obtain the debug key hash:

keytool -exportcert -alias androiddebugkey -keystore 
      ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

The default password for the debug keystore is android.

On Windows it will be necessary to install OpenSSL before the key hash can be generated. A copy of OpenSSL for Windows can be downloaded using the following link:

https://sourceforge.net/projects/openssl

Once OpenSSL has been installed, run the following command within a Command Prompt window to generate the debug key hash:

keytool -exportcert -alias androiddebugkey -keystore   
  %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

To generate the release key hash before uploading an app to the app store, the following command will need to be executed (where <key name> and <path to keystore> are replaced by the name given to the key and the location of the release keystore file specified when the key was created):

keytool -exportcert -alias <key name>  -keystore <path to keystore> | 
		openssl sha1 -binary | openssl base64

Once the key hash has been generated, it needs to be added to the app configuration within the Facebook for Developers portal. With the app selected in the Facebook portal, select the basic settings option in the navigation panel. Within the settings screen, click on the Add Platform option as shown in Figure 7-9:


Firebase auth facebook add platform.png

Figure 7-9


From the list of platforms, select the Android option. An additional section will then appear within the settings screen including a field titled Key Hashes. Copy the debug key hash generated by the keytool utility and paste it into this field before clicking on the Save Changes button:


Firebase auth facebook key hashes.png

Figure 7-10


When you have an app ready to be published, return to these settings and paste in the release hash key into the same field.

Modifying the App

With the work complete in the Firebase console and Facebook for Developers portal, there are now three more tasks that need to be accomplished before Facebook Login can be used within the example app. The first task is to add a string declaration within the strings.xml file containing the Facebook App ID. With the FirebaseAuth project loaded into Android Studio, use the project tool window to open the app -> res -> values -> strings.xml file. With the file loaded into the editor, add a new string entity with the name facebook_application_id as follows where <your_fb_app_id> is replaced by the actual App ID assigned within the Facebook portal:

<resources>
    <string name="app_name">FirebaseAuth</string>
    <string name="facebook_application_id" 
		translatable="false"><your_fb_app_id></string>
</resources> 

Next, two new elements need to be added to the project manifest file, one to grant internet access permission to the app, and the other to assign the facebook_application_id string created above to the ApplicationId property of the Facebook SDK. Within the project tool window, select the manifests -> AndroidManifest.xml file and edit it to add these additional elements:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ebookfrenzy.firebaseauth">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".FirebaseAuthActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SignedInActivity"></activity>

        <meta-data android:name="com.facebook.sdk.ApplicationId" 
	    android:value="@string/facebook_application_id"/>

    </application>

</manifest>

You are reading a sample chapter from the Firebase Essentials - Android Edition book.

Purchase the full edition of this book in eBook ($19.99) or Print ($38.99) format.
Firebase Essentials - Android Edition Print and eBook (ePub/PDF/Kindle) edition contains 55 chapters and 23 example apps. Learn more...

Buy eBook Buy Print Preview Book

Next, edit the module level build.gradle file and add a dependency for the facebook-android-sdk library:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.firebaseui:firebase-ui:2.0.1'
compile 'com.firebaseui:firebase-ui-auth:2.0.1'
compile('com.facebook.android:facebook-android-sdk:4.23.0')
testCompile 'junit:junit:4.12'

The final task before testing the Facebook Login provider is to add a single line of code to include Facebook Login in the list of supported providers. Remaining within Android Studio, edit the FirebaseAuthActivity.java file, locate the getProviderList() method and modify it to add the Facebook Login provider:

private List<AuthUI.IdpConfig> getProviderList() {

    List<AuthUI.IdpConfig> providers = new ArrayList<>();

    providers.add(new 
	AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build());
    providers.add(new 
	AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
    providers.add(new 
	AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build());

    return providers;
}

Testing Facebook Login Authentication

Compile and run the FirebaseAuth app on a physical Android device or emulator. If the Smart Lock dialog appears, tap on the None of the Above option to display the provider selection screen where a Facebook button will now be shown along with the Google and email provider options:


Firebase auth signin three providers.png

Figure 7-11


After selecting the Sign in with Facebook button, the exact Facebook sign in screen that appears will depend on whether the Facebook app is also installed on the device. If the Facebook app is not currently installed on the device, the screen shown in Figure 7-12 will appear. This is known as the fallback login screen and is actually a login screen loaded into a WebView instance:


Firebase auth facebook web signing.png

Figure 7-12


If, on the other hand, the Facebook app is installed on the device, the provider will redirect the login to the app and the sign-in screen will resemble Figure 7-13:


Firebase auth facebook app signin.png

Figure 7-13


Sign in using a valid Facebook account and note that the account name, email address and profile photo all appear within the SignedInActivity layout.

Open a browser window and navigate to the list of users on the Authentication page for the Firebase Examples project where the Facebook account used to gain access to the app will now listed. Since this account was created using the Facebook Login provider, a Facebook logo is included in the Provider column:


Firebase auth console facebook users.png

Figure 7-14


Summary

Integrating Facebook Login as a provider within a Firebase authentication configuration is a multistep process which involves creating and configuring an app within the Facebook developer portal, implementing the correct settings within the Firebase console and making project and code changes to the app project within Android studio. Once these steps have been performed as outlined in this chapter, users are able to create accounts and sign into the app using their Facebook credentials.


You are reading a sample chapter from the Firebase Essentials - Android Edition book.

Purchase the full edition of this book in eBook ($19.99) or Print ($38.99) format.
Firebase Essentials - Android Edition Print and eBook (ePub/PDF/Kindle) edition contains 55 chapters and 23 example apps. Learn more...

Buy eBook Buy Print Preview Book



PreviousTable of ContentsNext
Google Sign-In Authentication using FirebaseUI AuthTwitter Sign-In Authentication using FirebaseUI Auth