Ionic 5+/Angular环境下Firebase reauthenticateWithCredential凭证无效报错的解决方案咨询
Hey there, the issue here is that the credential you're getting from signInWithEmailAndPassword isn't valid for re-authentication—and that's because for email/password auth, the credential property returned by signInWithEmailAndPassword is actually null. Firebase doesn't expose the credential via that method; instead, you need to construct it directly using the user's email and password.
Here's the corrected version of your code, with explanations:
import { EmailAuthCredential } from '@angular/fire/auth'; // Make sure to import this async reAuthenticateUser({ email, password }) { const user = await this.afAuth.currentUser; if (!user) { // Handle case where no user is logged in throw new Error('No user currently authenticated'); } // Create a valid EmailAuthCredential directly from email and password const credential = EmailAuthCredential.fromEmailAndPassword(email, password); // Don't forget to await this call—it's asynchronous! await user.reauthenticateWithCredential(credential); }
Key fixes to note:
- Construct the credential directly: Use
EmailAuthCredential.fromEmailAndPassword()to generate a valid credential object specifically for email/password re-authentication. This is the correct way to create the credential Firebase expects for this method. - Await the re-authentication call: Your original code didn't await
user.reauthenticateWithCredential(), which means the operation might not complete before your code proceeds to other actions (like deleting the user). - Add error handling: I added a check for
!userto handle cases where no user is logged in, which prevents unexpected errors later.
Why didn't your original approach work? When you use signInWithEmailAndPassword, the returned UserCredential's credential field is only populated for federated auth providers (like Google, Facebook, etc.). For email/password auth, this field remains null—so you were passing a null value to reauthenticateWithCredential, hence the "invalid credential" error.
内容的提问来源于stack exchange,提问作者adit bharadwaj

