Firebase关联手机号至邮箱密码账号时遇[auth/unsupported-first-factor]错误
问题原因分析
- 概念混淆:MFA因子 vs 登录凭证
你在创建用户时,直接将手机号设置为了MFA第二验证因子,但需求是把手机号作为**登录凭证(第一因子)**实现双登录。二者完全不同:
- MFA因子是登录时的二次验证手段,不能直接用来登录账号;
- 登录凭证是可独立用于登录的身份标识(如邮箱、手机号)。
前端代码逻辑错误
你在用户已登录的状态下调用了resolve.resolveSignIn(multiFactorAssertion)——这个方法是用于首次登录时完成MFA验证的流程,而非关联手机号作为登录凭证的流程。当前用户已通过邮箱密码登录,无需再走MFA登录校验,因此触发unsupported-first-factor错误。账号状态冲突
由于创建用户时已将手机号注册为MFA因子,此时尝试用linkWithCredential将其关联为登录凭证,会因手机号已被占用为MFA因子而失败。
解决方案
步骤1:调整用户创建逻辑
先创建仅包含邮箱密码的账号,移除创建时的MFA配置:
const user = await firebase.auth().createUser({ email, password, emailVerified: true // 移除multiFactor相关配置 });
步骤2:修改前端OTP验证关联逻辑
用户通过邮箱密码登录后,直接验证手机号并关联为登录凭证,无需MFA相关代码:
const onVerifyOtp = async (otp: string) => { try { setLoading(true); // 生成手机号凭证 const credential = auth.PhoneAuthProvider.credential(verificationId, otp); // 直接关联当前登录用户与手机号凭证 const linkedUser = await auth().currentUser.linkWithCredential(credential); const newuser = new UserInterface(); newuser.id = linkedUser.user?.uid || ''; newuser.phoneNumber = linkedUser.user?.phoneNumber || ''; newuser.otpRequested = true; setLoading(false); setLogins(0); setUser(newuser); setUserData(newuser); } catch (err: any) { setError(invalidOtp); setLoading(false); logger.log(err); } }
(可选)同时启用MFA(双登录+二次验证)
如果需要既支持双登录,又需要MFA验证,可在关联手机号为登录凭证后,再将其设置为MFA因子:
// 关联手机号后,添加MFA因子 const addMfaFactor = async () => { const user = auth().currentUser; if (!user) return; // 重新获取手机号凭证(或复用之前的credential) const phoneCredential = auth.PhoneAuthProvider.credential(verificationId, otp); const multiFactorAssertion = auth.PhoneMultiFactorGenerator.assertion(phoneCredential); await user.multiFactor.enroll(multiFactorAssertion, "手机号验证"); }
内容的提问来源于stack exchange,提问作者Muteshi
相关产品推荐
相关产品推荐

