การยืนยันตัวตนหลายปัจจัย (MFA)
เพิ่มความปลอดภัยด้วยการเปิดใช้และกำหนดค่าการยืนยันตัวตนหลายปัจจัยสำหรับผู้ใช้ไฟร์เบส
การยืนยันตัวตนหลายปัจจัย (MFA) เป็นบทเรียน Firebase Auth & Realtime Database Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Firebase Auth & Realtime Database Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Firebase Auth & Realtime Database Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Secure Your App with MFA
Multi-Factor Authentication (MFA) adds an extra layer of security to user accounts. Instead of just a password, users need a second "factor" to prove their identity.
This significantly reduces the risk of unauthorized access, even if a password is stolen.
Firebase MFA Overview
Firebase Authentication provides built-in support for MFA. It allows users to enroll multiple second factors, like a phone number for SMS verification.
When MFA is enabled, users first sign in with their primary method (e.g., email/password), then complete a challenge with one of their enrolled second factors.
Prerequisites for MFA
To enable MFA for a user, they must first be signed into your app. Firebase MFA works by associating additional factors with an existing user account.
- User must be signed in.
- Firebase SDK initialized.
- You'll guide the user to enroll a second factor.
Adding a Phone Factor
A common second factor is a phone number, verified via SMS. This process involves:
- Sending a verification code to the user's phone.
- The user entering that code into your app.
- Firebase verifying the code and linking the phone number to the user's account.
Start Phone Enrollment
Here's how to initiate sending an SMS verification code to a user's phone number as an MFA factor. Remember to replace +16505551234 with the user's actual phone number.
import com.google.firebase.auth.*;
import com.google.firebase.FirebaseApp;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
// Assume FirebaseApp is initialized and a user is signed in.
// FirebaseAuth auth = FirebaseAuth.getInstance();
// FirebaseUser user = auth.getCurrentUser(); // Must be non-null
System.out.println("Simulating MFA phone enrollment initiation:");
// Example PhoneAuthOptions (actual implementation requires Activity context)
PhoneAuthOptions options = PhoneAuthOptions.newBuilder(FirebaseAuth.getInstance())
.setPhoneNumber("+16505551234") // User's phone number
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(null) // Use 'this' for Activity context on Android
.setCallbacks(new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override public void onVerificationCompleted(PhoneAuthCredential credential) { /* auto-verified */ }
@Override public void onVerificationFailed(FirebaseException e) { System.err.println("Failed: " + e.getMessage()); }
@Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
System.out.println("Code sent. Store verificationId: " + verificationId);
// Prompt user for SMS code here.
}
}).build();
// In a real app: PhoneAuthProvider.verifyPhoneNumber(options);
System.out.println("SMS verification initiated (simulated).");
}
}Verify & Finalize Enrollment
Once the user receives the SMS code and enters it, you use the verificationId (from the previous step) and the code to create a PhoneAuthCredential, then enroll it as an MFA factor.
import com.google.firebase.auth.*;
public class Main {
public static void main(String[] args) {
// Assume FirebaseApp is initialized and a user is signed in.
// FirebaseAuth auth = FirebaseAuth.getInstance();
// FirebaseUser user = auth.getCurrentUser(); // Must be non-null
String verificationId = "YOUR_VERIFICATION_ID"; // From onCodeSent callback
String smsCode = "123456"; // User's input
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, smsCode);
// Enroll the credential as an MFA factor
// user.multiFactor.enroll(credential)
// .addOnCompleteListener(task -> {
// if (task.isSuccessful()) {
// System.out.println("MFA factor enrolled successfully!");
// } else {
// System.err.println("MFA factor enrollment failed: " + task.getException().getMessage());
// }
// });
System.out.println("MFA enrollment code demonstrated. Actual enrollment is async.");
}
}Authenticating with MFA
When a user with MFA enabled tries to sign in, the initial sign-in (e.g., with email/password) might return a MultiFactorResolver. This resolver contains information about the available second factors.
Your app then prompts the user to select and verify one of their enrolled factors.
Respond to MFA Challenge
After a primary sign-in, if MFA is required, you'll get a MultiFactorResolver. You then use this to complete the sign-in with a second factor, such as a phone SMS code.
import com.google.firebase.auth.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Assume FirebaseApp is initialized.
// FirebaseAuth auth = FirebaseAuth.getInstance();
// --- Scenario: After an initial sign-in attempt (e.g., email/password)
// --- that requires MFA, you would receive a MultiFactorResolver.
// --- This is a simplified demo.
System.out.println("Simulating MFA sign-in challenge response:");
// MultiFactorResolver resolver = ... (obtained from initial sign-in result)
// For demonstration, let's mock a resolver context.
// In a real app, you'd get this from a FirebaseAuthException.
// Example of how you'd get enrolled factors from a resolver
// List<MultiFactorInfo> factors = resolver.getFactors();
// if (!factors.isEmpty()) {
// MultiFactorInfo selectedFactor = factors.get(0); // Choose one, e.g., phone
// if (selectedFactor.getFactorId().equals(PhoneMultiFactorGenerator.FACTOR_ID)) {
// // Initiate SMS verification for this factor
// // Then, get the SMS code from the user
// // String smsCode = "123456";
// // PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, smsCode);
// // MultiFactorAssertion assertion = PhoneMultiFactorGenerator.getAssertion(credential);
//
// // auth.signInWithMultiFactorCredential(resolver.resolveSignIn(assertion))
// // .addOnCompleteListener(task -> {
// // if (task.isSuccessful()) {
// // System.out.println("Signed in successfully with MFA!");
// // } else {
// // System.err.println("MFA sign-in failed: " + task.getException().getMessage());
// // }
// // });
// }
// }
System.out.println("MFA sign-in challenge response simulated. See comments.");
}
}View & Unenroll Factors
Users can manage their enrolled MFA factors. This includes viewing a list of factors they've added and removing (unenrolling) factors they no longer wish to use.
This is crucial for user control and security, allowing them to revoke access for lost devices.
import com.google.firebase.auth.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Assume FirebaseApp is initialized and a user is signed in.
// FirebaseAuth auth = FirebaseAuth.getInstance();
// FirebaseUser user = auth.getCurrentUser(); // Must be non-null
if (user != null) {
System.out.println("Managing MFA factors for user: " + user.getUid());
// Get enrolled factors
List<MultiFactorInfo> enrolledFactors = user.getMultiFactor().getEnrolledFactors();
System.out.println("\nEnrolled factors:");
if (enrolledFactors.isEmpty()) {
System.out.println(" No MFA factors enrolled.");
} else {
for (MultiFactorInfo factor : enrolledFactors) {
System.out.println(" - Factor ID: " + factor.getFactorId() + ", Display Name: " + factor.getDisplayName());
// Example: unenroll the first factor
// user.getMultiFactor().unenroll(factor)
// .addOnCompleteListener(task -> {
// if (task.isSuccessful()) {
// System.out.println("Factor unenrolled successfully: " + factor.getFactorId());
// } else {
// System.err.println("Failed to unenroll: " + task.getException().getMessage());
// }
// });
}
}
} else {
System.out.println("No user signed in to manage MFA factors.");
}
}
}MFA Quick Check
Which of the following is NOT a typical step when a user with MFA enabled signs into a Firebase application?
MFA: Stronger Security
In this lesson, you learned how to enhance your application's security by implementing Firebase Multi-Factor Authentication (MFA).
- We covered enrolling new MFA factors, specifically phone numbers.
- We explored how to handle the MFA challenge during user sign-in.
- You also saw how users can manage their enrolled factors.
MFA is a powerful tool to protect user accounts from unauthorized access.
คำถามที่พบบ่อย
บทเรียน “การยืนยันตัวตนหลายปัจจัย (MFA)” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การยืนยันตัวตนหลายปัจจัย (MFA)” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Firebase Auth & Realtime Database Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Firebase Auth & Realtime Database Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การยืนยันตัวตนหลายปัจจัย (MFA)”
เพิ่มความปลอดภัยด้วยการเปิดใช้และกำหนดค่าการยืนยันตัวตนหลายปัจจัยสำหรับผู้ใช้ไฟร์เบส คุณปฏิบัติ Firebase Auth & Realtime Database Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Firebase Auth & Realtime Database Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Firebase Auth & Realtime Database Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การยืนยันตัวตนหลายปัจจัย (MFA)” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Firebase Auth & Realtime Database Apps นี้ได้ไหม
ได้ บทเรียน Firebase Auth & Realtime Database Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การยืนยันตัวตนด้วยหมายเลขโทรศัพท์
- การยืนยันตัวตนหลายปัจจัย (MFA)
- ข้ออ้างสิทธิ์แบบกำหนดเองและกฎความปลอดภัย
- การเชื่อมโยงบัญชีและการจัดการผู้ให้บริการ