Firebase Authentication
# CHAPTER 23
Firebase Authentication
1. Introduction
Until now, our application has been stateless regarding identity. Every user experiences the exact same app, and data cannot be synchronized across multiple devices securely. Building a custom backend server to handle hashed passwords, security tokens, and email verification is incredibly complex and dangerous if done incorrectly. Enter Firebase, Google's Backend-as-a-Service (BaaS) platform. Firebase provides secure, pre-built infrastructure for authentication, databases, storage, and analytics. In this chapter, we will master Firebase Authentication. We will connect our Android project to the Firebase Console, implement secure Email and Password registration, manage active user sessions, and build a robust login architecture.2. Learning Objectives
By the end of this chapter, you will be able to:- Connect an Android Studio project to a Google Firebase project.
-
Configure the
google-services.jsonfile and Gradle dependencies.
- Implement the Email/Password User Registration flow.
- Implement the User Sign-In and Sign-Out functionality.
- Check the current session state to route users to the Dashboard or the Login screen.
- Handle Firebase asynchronous Tasks and Exceptions gracefully.
3. Step 1: Connecting to Firebase
Before writing code, we must register our app with Google.- 1. Go to the Firebase Console in your browser.
- 2. Click "Add Project", name it (e.g., "KotlinCourseApp"), and disable Google Analytics for now.
- 3. Once created, click the Android Icon to add an app.
-
4.
Enter your Android Package Name (found at the top of your
MainActivity.kt, e.g.,com.example.myapp).
-
5.
Download the
google-services.jsonfile.
-
6.
Switch Android Studio to "Project" view and drag the
google-services.jsonfile directly into theappfolder.
4. Step 2: Gradle Configuration
Firebase requires specific Google Services plugins to read the JSON file.In your project-level build.gradle.kts (or build.gradle):
Add the Google Services dependency inside buildscript { dependencies { ... } } or in the plugins block depending on your Gradle version.
In your app-level build.gradle.kts (Module :app):
Apply the plugin at the top, and add the Authentication dependency:
*Click "Sync Now"!* Finally, go back to the Firebase Console in your browser, click Authentication -> Get Started, and explicitly enable the Email/Password sign-in provider.
5. Step 3: Registering a New User (Sign Up)
Firebase handles all password hashing and server communication in the background. We simply pass it an email and password using theFirebaseAuth instance.
6. Step 4: Signing In an Existing User
The logic for logging in is nearly identical, utilizingsignInWithEmailAndPassword.
7. Step 5: Session Management (Routing)
When a user closes the app and reopens it, they shouldn't have to log in again. Firebase automatically saves a secure session token locally. In yourSplashActivity or MainActivity, check if a currentUser exists. If they exist, skip the login screen!
8. Step 6: Signing Out
Signing out destroys the local session token.9. Firebase Coroutines (Advanced)
Firebase Tasks (addOnCompleteListener) use standard callbacks, which can lead to nested "Callback Hell". Modern Android architecture uses Coroutines. The kotlinx-coroutines-play-services library provides .await(), allowing you to execute Firebase calls sequentially inside viewModelScope.
*(Requires: implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3"))*
10. Common Mistakes
-
Forgetting to Enable the Provider: Spending 3 hours debugging code because
createUserWithEmailAndPasswordthrows an error, only to realize you never clicked the toggle to enable "Email/Password" inside the Firebase Web Console.
-
Leaking the Login Screen: Using
startActivityto go to the Dashboard without callingfinish(). If the user hits the physical back button on their phone, they will return to the Login screen despite being fully logged in!
11. Best Practices
-
UX Feedback: Firebase network calls take 1–3 seconds. Always show a
ProgressBarwhen the user clicks "Submit", and disable the button to prevent them from clicking it 5 times and initiating 5 simultaneous network requests.
12. Exercises
-
1.
Setup a Firebase project and successfully sync the
google-services.jsonwith an empty Android app.
- 2. Build a simple UI with two EditTexts and a "Register" button. Implement the Firebase Registration logic.
13. Coding Challenges
Challenge: Implement "Password Reset" functionality. Research theauth.sendPasswordResetEmail(email) method. Create a "Forgot Password?" button that extracts the email from the EditText and sends a Firebase password reset link, displaying a Toast on success.
14. MCQ Quiz with Answers
What critical functional role does the google-services.json file play in the Firebase Authentication architecture?
When designing the initial application routing logic within onStart(), how does a developer definitively ascertain if an active user session persists from a previous application launch?
15. Interview Questions
-
Q: Explain the structural hazards of utilizing traditional nested Callbacks (
addOnCompleteListener) for Firebase authentication logic within a robust MVVM architecture. How does utilizing Coroutines and the.await()extension function mitigate these issues?
-
Q: Detail the user experience (UX) and architectural imperatives of utilizing
finish()or Intent flag manipulation (FLAG_ACTIVITY_CLEAR_TASK) immediately following a successful Firebase login execution.
- Q: Describe how Firebase manages session persistence. Under what programmatic conditions is the local authentication token invalidated?