Easy Facebook Authentication in Jetpack Compose with Firebase

Integrating user authentication into your Android app is a fundamental requirement in modern mobile app development. Among the popular authentication methods, Facebook login is a user-friendly and widely used choice. In this blog post, we’ll explore how to implement Facebook Authentication in Jetpack Compose using Firebase, focusing on seamless integration and best practices for intermediate and advanced developers.

Why Facebook Authentication?

Facebook login allows users to sign into your app using their Facebook accounts, enhancing the user experience by eliminating the need to remember separate login credentials. Some advantages include:

  1. Wide Adoption: Facebook has a massive user base.

  2. Ease of Use: Login with a single tap.

  3. Secure Authentication: OAuth 2.0 protocol ensures security.

By combining Firebase Authentication with Jetpack Compose, you can build a robust and modern login experience.

Prerequisites

Before we dive into the implementation, ensure you have the following setup:

  1. Android Studio Arctic Fox or Newer: Jetpack Compose requires a modern IDE version.

  2. Firebase Project: A Firebase project linked to your app.

  3. Facebook Developer Account: Create a Facebook app for generating the App ID and secret.

  4. Dependencies: Add the required libraries to your project.

Step 1: Setting Up Firebase Authentication

  1. Add Firebase to Your Project:

    • Navigate to the Firebase Console, create a project, and add your Android app.

    • Download the google-services.json file and place it in your app’s src/main directory.

  2. Enable Facebook Authentication:

    • Go to the Authentication section in Firebase Console.

    • Select Sign-in Method and enable Facebook Provider.

    • Enter your Facebook App ID and App Secret (available in your Facebook developer account).

  3. Update App Credentials:

    • Add the Facebook Login credentials to your app's manifest:

      <meta-data
          android:name="com.facebook.sdk.ApplicationId"
          android:value="@string/facebook_app_id" />
    • Define facebook_app_id in res/values/strings.xml.

Step 2: Adding Required Dependencies

In your app-level build.gradle file, add the following dependencies:

implementation platform('com.google.firebase:firebase-bom:32.0.0')
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.facebook.android:facebook-login:latest.release'
implementation 'androidx.compose.ui:ui:1.4.0'
implementation 'androidx.compose.material:material:1.4.0'

Sync your project to download the dependencies.

Step 3: Configuring Facebook SDK

  1. Initialize Facebook SDK: In your MainActivity, initialize the Facebook SDK:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FacebookSdk.sdkInitialize(applicationContext)
    }
  2. Add Callback Manager: Create a CallbackManager instance to handle login responses:

    val callbackManager = CallbackManager.Factory.create()

Step 4: Implementing Facebook Login in Jetpack Compose

Let’s dive into the Jetpack Compose implementation.

Facebook Login Button

Jetpack Compose doesn’t provide a built-in Facebook login button, but you can use a custom Composable:

@Composable
fun FacebookLoginButton(onClick: () -> Unit) {
    Button(
        onClick = onClick,
        colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)
    ) {
        Text(text = "Login with Facebook", color = Color.White)
    }
}

Handling Login Logic

In your MainActivity, set up the login process:

val auth = FirebaseAuth.getInstance()
val callbackManager = CallbackManager.Factory.create()

fun loginWithFacebook() {
    LoginManager.getInstance().logInWithReadPermissions(
        this, listOf("email", "public_profile")
    )

    LoginManager.getInstance().registerCallback(callbackManager,
        object : FacebookCallback<LoginResult> {
            override fun onSuccess(loginResult: LoginResult) {
                val accessToken = loginResult.accessToken
                val credential = FacebookAuthProvider.getCredential(accessToken.token)

                auth.signInWithCredential(credential).addOnCompleteListener { task ->
                    if (task.isSuccessful) {
                        // Login successful
                        Log.d("FacebookAuth", "Success: ${auth.currentUser?.email}")
                    } else {
                        Log.e("FacebookAuth", "Error: ${task.exception?.message}")
                    }
                }
            }

            override fun onCancel() {
                Log.d("FacebookAuth", "Login canceled")
            }

            override fun onError(error: FacebookException) {
                Log.e("FacebookAuth", "Error: ${error.message}")
            }
        })
}

Integrating with Jetpack Compose

Call the loginWithFacebook() function when the button is clicked:

@Composable
fun FacebookAuthScreen() {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        FacebookLoginButton(onClick = { loginWithFacebook() })
    }
}

Finally, set this screen as the content of your activity:

setContent {
    FacebookAuthScreen()
}

Step 5: Handling Activity Result

Override onActivityResult in your activity to handle the Facebook login callback:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    callbackManager.onActivityResult(requestCode, resultCode, data)
}

Best Practices

  1. Secure Your App:

    • Use HTTPS for all API calls.

    • Regularly update dependencies to address security vulnerabilities.

  2. Handle Errors Gracefully:

    • Provide clear error messages for users.

    • Log errors for debugging.

  3. Test Thoroughly:

    • Test login functionality on multiple devices and scenarios.

  4. UI Optimization:

    • Ensure the login button aligns with your app’s design language.

Conclusion

By integrating Facebook authentication in Jetpack Compose with Firebase, you can provide a modern and seamless login experience for your users. With the power of Compose’s declarative UI and Firebase’s robust authentication system, this implementation is both efficient and user-friendly. Follow the steps outlined here, and you’ll be on your way to building a professional-grade authentication flow.

For further reading, explore Firebase Documentation and Facebook Login for Android.