如何实现类似WhatsApp的Firebase每次登录重新验证手机号功能
Got it, let's walk through how to build that WhatsApp-style mandatory phone verification for every login using Firebase Phone Auth. You’ve already got a code snippet started—let’s expand it and lock in the logic to ensure users can’t skip verification on any login attempt:
First, regardless of whether a user was logged in before, you need to force the phone verification flow every time they open the app or navigate to the login screen. That means skipping Firebase’s default persistent login and starting the verification process immediately.
Here’s how to adjust your activity setup:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Even if a user was previously logged in, we sign them out first to enforce re-verification FirebaseAuth.getInstance().signOut(); // Start the phone verification flow right away (replace with user-inputted phone number) startPhoneVerification("+1234567890"); } private void startPhoneVerification(String phoneNumber) { PhoneAuthProvider.getInstance().verifyPhoneNumber( phoneNumber, 60, TimeUnit.SECONDS, this, new PhoneAuthProvider.OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) { // Auto-verification succeeded (e.g., trusted device), proceed to sign in signInWithPhoneAuthCredential(phoneAuthCredential); } @Override public void onVerificationFailed(FirebaseException e) { // Handle verification errors (invalid number, network issues, etc.) Toast.makeText(LoginActivity.this, "Verification failed: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } @Override public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) { super.onCodeSent(verificationId, token); // Navigate to OTP input screen, pass verification ID and resend token Intent otpIntent = new Intent(LoginActivity.this, OtpInputActivity.class); otpIntent.putExtra("VERIFICATION_ID", verificationId); otpIntent.putExtra("RESEND_TOKEN", token); startActivity(otpIntent); } } ); }
Firebase Auth automatically persists user sessions by default, which means users would stay logged in even after closing the app. To fully enforce re-verification every time, disable this persistence—just make sure to call this before any other Firebase Auth operations:
Add this to your custom Application class (create one if you don’t have it):
public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); // Disable persistent authentication to force re-verification on app restart FirebaseAuth.getInstance().setPersistenceEnabled(false); } }
Don’t forget to register this Application class in your AndroidManifest.xml.
Once the user receives the OTP, they’ll enter it in the dedicated input screen. Here’s how to validate the code and complete the login—this step ensures only verified users get access:
// Inside OtpInputActivity private void validateOtp(String userOtp) { String verificationId = getIntent().getStringExtra("VERIFICATION_ID"); PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, userOtp); signInWithPhoneAuthCredential(credential); } private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) { FirebaseAuth.getInstance().signInWithCredential(credential) .addOnCompleteListener(this, task -> { if (task.isSuccessful()) { // Login succeeded—navigate to main app and clear back stack FirebaseUser user = task.getResult().getUser(); Toast.makeText(OtpInputActivity.this, "Welcome back!", Toast.LENGTH_SHORT).show(); Intent mainIntent = new Intent(OtpInputActivity.this, MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(mainIntent); finishAffinity(); } else { // Handle invalid OTP or other login errors if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) { Toast.makeText(OtpInputActivity.this, "Invalid OTP code", Toast.LENGTH_SHORT).show(); } } }); }
To prevent any edge cases where a user might bypass the verification flow, add a check in your main activity’s onCreate to redirect to login if no verified user exists:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser == null) { // No verified user—send back to login startActivity(new Intent(MainActivity.this, LoginActivity.class)); finish(); } }
Key Notes:
- Never add a "remember me" option—WhatsApp’s flow relies on no persistent sessions for this verification step.
- Ensure the phone number is always collected fresh or validated against stored data (avoid hardcoding, obviously).
内容的提问来源于stack exchange,提问作者HAMZAA

