Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🔍 Overview
Authentication is one of the most crucial aspects of any
mobile or web application. It ensures security, personalizes user experiences,
and enables access control. Firebase Authentication is a powerful service that
simplifies the entire authentication process—be it email/password, social
sign-ins, or even anonymous access—while maintaining top-tier security and ease
of use.
In this chapter, we’ll explore Firebase Authentication in
detail, how to implement it in your mobile app, manage users, and apply
role-based access control using custom claims.
🔐 What is Firebase
Authentication?
Firebase Authentication provides backend services,
easy-to-use SDKs, and ready-made UI libraries to authenticate users to your
app. It supports:
It also integrates seamlessly with Firestore, Realtime
Database, and other Firebase services.
🔧 Why Use Firebase Auth?
🔹 Benefits:
🧱 Firebase Auth
Architecture
Firebase uses a token-based system built on OAuth 2.0
and JWT (JSON Web Tokens). Here’s a high-level architecture:
text
[User Interaction]
↓
[Firebase Auth SDK]
↓
[Authentication Provider (Google, Facebook, etc.)]
↓
[Firebase Auth Server]
↓
[Access Token Issued to App]
↓
[Used to Access Firestore, Realtime DB, etc.]
🧰 Supported Sign-In
Methods
Method |
Description |
Use Case |
Email &
Password |
Standard
authentication |
Generic app login |
Google Sign-In |
OAuth with
Google account |
Apps with
Google user base |
Facebook Login |
Facebook OAuth-based
login |
Social or media apps |
Phone Number |
OTP-based
login |
Regional
apps, delivery apps |
Anonymous |
Guest user login |
Try-before-login apps,
games |
Custom Authentication |
Use external
auth systems |
Enterprise or
secure networks |
🚀 Setting Up Firebase
Authentication
🔸 Step 1: Enable Sign-in
Method
🔸 Step 2: Add Firebase
Auth to Your App
Android (Java/Kotlin) Example:
groovy
//
In build.gradle
implementation
'com.google.firebase:firebase-auth:22.1.0'
🔸 Step 3: Initialize
Firebase in App
java
FirebaseAuth
mAuth = FirebaseAuth.getInstance();
🧪 Code Samples
✅ Email/Password Signup
java
mAuth.createUserWithEmailAndPassword("test@example.com",
"123456")
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser user =
mAuth.getCurrentUser();
Log.d("FirebaseAuth",
"User Created: " + user.getEmail());
} else {
Log.w("FirebaseAuth",
"Error: ", task.getException());
}
});
✅ Sign In with Email/Password
java
mAuth.signInWithEmailAndPassword("test@example.com",
"123456")
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser user =
mAuth.getCurrentUser();
Log.d("FirebaseAuth",
"Login Successful: " + user.getEmail());
} else {
Log.w("FirebaseAuth",
"Login Failed: ", task.getException());
}
});
✅ Sign Out
java
mAuth.signOut();
✅ Get Current Logged-In User
java
FirebaseUser
currentUser = mAuth.getCurrentUser();
if
(currentUser != null) {
String email = currentUser.getEmail();
String uid = currentUser.getUid();
}
✅ Update User Profile
java
FirebaseUser
user = FirebaseAuth.getInstance().getCurrentUser();
if
(user != null) {
UserProfileChangeRequest profileUpdates =
new UserProfileChangeRequest.Builder()
.setDisplayName("John Doe")
.build();
user.updateProfile(profileUpdates);
}
🔐 Role-Based Access
Control with Custom Claims
Firebase Admin SDK (Node.js) allows setting custom claims
like "admin", "editor", etc.
js
admin.auth().setCustomUserClaims(uid,
{ admin: true })
.then(() => {
console.log('Custom claim set for user');
});
You can then use these claims in Firestore rules:
js
match
/adminData/{docId} {
allow read, write: if
request.auth.token.admin == true;
}
📋 Firebase Authentication
Management Table
Feature |
SDK Support |
Console Access |
Server-side
Available |
Customizable |
User Registration |
Yes |
No |
Yes (Admin SDK) |
Yes |
Password Reset Email |
Yes |
Yes |
Yes |
Yes |
Delete Account |
Yes |
No |
Yes |
No |
Add/Update Profile |
Yes |
No |
Yes |
Yes |
Email Verification |
Yes |
No |
Yes |
Partial |
Custom Claims |
No |
No |
Yes |
Yes |
🌐 Firebase Auth UI
Library
Firebase also offers FirebaseUI—a drop-in
authentication UI that handles sign-in flows for you.
groovy
implementation 'com.firebaseui:firebase-ui-auth:8.0.2'
You can then launch an auth intent like:
java
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(Arrays.asList(
new
AuthUI.IdpConfig.EmailBuilder().build(),
new
AuthUI.IdpConfig.GoogleBuilder().build()
))
.build(),
RC_SIGN_IN);
🔒 Securing Access with
Authentication State
Firebase provides AuthStateListeners so you can
redirect or protect screens based on login status.
java
FirebaseAuth.AuthStateListener
mAuthListener = firebaseAuth -> {
FirebaseUser user =
firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
}
};
📌 Conclusion
Firebase Authentication offers a robust, scalable, and
developer-friendly authentication system that can be integrated in just
minutes. Whether you’re building a small MVP or a global app, Firebase Auth
provides the flexibility and security needed to manage users, sessions, roles,
and access controls efficiently.
In the next chapter, we’ll explore Firebase’s databases:
Realtime Database and Firestore—where you’ll learn how to store and sync
user-generated content.
Firebase is a Backend-as-a-Service (BaaS) platform by Google that offers a suite of tools like real-time databases, authentication, cloud storage, hosting, and analytics—enabling developers to build fully functional mobile apps without managing servers.
Yes, Firebase supports Android, iOS, and even cross-platform frameworks like Flutter and React Native, offering SDKs and libraries that make integration smooth across platforms.
Realtime Database is a low-latency JSON-based database ideal for syncing data in real-time. Firestore, on the other hand, is more scalable, supports structured collections/documents, and offers more advanced querying and offline support.
Absolutely. Firebase Authentication supports email/password, phone number, and social logins with built-in security, encrypted data transmission, and session management.
Yes, through Firebase Cloud Functions, you can write server-side logic (like sending notifications, validating data, or processing payments) that runs in response to events—all without managing physical servers.
Firebase offers a free-tier plan (Spark Plan) which includes many core features. As your usage grows, you can switch to the Blaze Plan (pay-as-you-go), which scales with your app's needs.
Firebase is built on Google Cloud infrastructure, making it highly scalable. Cloud Firestore and Cloud Functions scale automatically based on usage, ideal for apps with growing user bases.
Yes, Firebase is modular. You can use only the features you need—like Authentication or Cloud Messaging—without being forced to use the whole stack.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)