[英]How to update authentication token in Firebase with Flutter
I'm making an app with Flutter and Firebase but I'm having issues with the "email_verified" check in Firebase Rules.我正在使用 Flutter 和 Firebase 制作应用程序,但我在 Firebase 规则中遇到“email_verified”检查问题。 I want to grant read access to documents only if the user has their email verified.
我想仅在用户已验证其 email 时授予对文档的读取权限。 The code seems to be correct, but when I create an account in my app and verify my email, I get a permission-denied error when trying to access the data in the documents.
代码似乎是正确的,但是当我在我的应用程序中创建一个帐户并验证我的 email 时,在尝试访问文档中的数据时出现权限被拒绝的错误。 I'm only able to read the data if I sign out and in again.
如果我退出并再次登录,我只能读取数据。 Therefore, I'm pretty sure the problem is that the auth token isn't being updated.
因此,我很确定问题是授权令牌没有更新。
I saw some questions about this (like this one Firebase firestore not updating email verification status ) but I wasn't able to apply the solution to my code, since I'm using Flutter and I wasn't able to find how to do that there.我看到了一些关于此的问题(比如这个Firebase firestore not updating email verification status )但我无法将解决方案应用于我的代码,因为我使用的是 Flutter 并且我无法找到如何做到这一点那里。
Here's the Firebase Rules code that is failing:这是失败的 Firebase 规则代码:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /posts_data/{postId} {
allow read: if request.auth.token.email_verified;
}
}
}
I'm not experienced with Firebase, so I would appreciate it if someone could tell me how exactly to force the auth token to update in Flutter.我没有使用 Firebase 的经验,所以如果有人能告诉我如何在 Flutter 中强制更新身份验证令牌,我将不胜感激。
You can force the token to update in Flutter by calling the reload()
method on the FirebaseUser
object after the email verification is complete. email验证完成后,可以在
FirebaseUser
object上调用reload()
方法,强制更新Flutter中的token。 Try the following code after email verification done: email 验证完成后尝试以下代码:
FirebaseAuth.instance.currentUser().then((user) async {
await user.reload();
});
This will update the user's Auth token with the latest information from the Firebase server, including the email verification status.这将使用来自 Firebase 服务器的最新信息更新用户的 Auth 令牌,包括 email 验证状态。
OR或者
You can directly use user.isEmailVerified()
when you try to access the unauthorized content just for debugging purposes.And you can also use FirebaseAuth.instance.currentUser().getIdToken()
to get the auth token and verify that as well here's the reference for that.当您尝试访问未经授权的内容时,您可以直接使用
user.isEmailVerified()
FirebaseAuth.instance.currentUser().getIdToken()
供参考。
Source: firebase_auth package资料来源: firebase_auth package
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.