Flutter Firebase邮箱密码登录成功但Credentials返回Null
问题原因
邮箱密码登录方式下,signInWithEmailAndPassword返回的UserCredential.credential字段本身就是null——这个字段仅针对第三方OAuth登录(如Google、Apple登录)才会填充凭证数据,属于Firebase Auth的正常设计,并非异常或集成错误。
解决方案
要获取用户的访问令牌,需从UserCredential.user对象中获取idToken(JWT格式,用于后端身份验证),具体实现如下:
- 登录成功后,从
userCredential中取出用户实例 - 调用
getIdToken()方法获取最新的idToken(该方法会自动刷新过期令牌)
修改后的代码示例:
try { setState(() => isLoading = true); final userCredential = await FirebaseAuth .instance .signInWithEmailAndPassword( email: email!, password: password!); // 获取用户idToken(即所需的accessToken) final idToken = await userCredential.user?.getIdToken(); print('idToken: $idToken'); if (mounted) { Provider.of<UserCredentialsProvider>( context, listen: false) .setUser(userCredential); Navigator.push( context, MaterialPageRoute( builder: (context) => const Home(), ), ); } } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { SimpleUtilities().errorSnackBar(context, snackbarData: 'No user linked with this email.'); } else if (e.code == 'wrong-password') { SimpleUtilities().errorSnackBar(context, snackbarData: 'Wrong password provided.'); } } catch (e) { SimpleUtilities().errorSnackBar(context, snackbarData: e.toString()); }
补充说明
idToken是短期有效的JWT令牌,默认有效期1小时,调用getIdToken()时若令牌已过期,Firebase会自动刷新并返回新令牌- 若需长期维持登录状态,可使用
user.refreshToken获取刷新令牌,用于后续主动刷新idToken - 控制台日志中
Notifying id token listeners about user的提示,已说明用户登录流程完全正常
内容的提问来源于stack exchange,提问作者siffat
相关产品推荐
相关产品推荐

