Home > front end >  How to update authentication token in Firebase with Flutter
How to update authentication token in Firebase with Flutter

Time:01-17

I'm making an app with Flutter and Firebase but I'm having issues with the "email_verified" check in Firebase Rules. I want to grant read access to documents only if the user has their email verified. 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. 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.

Here's the Firebase Rules code that is failing:

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.

CodePudding user response:

You can force the token to update in Flutter by calling the reload() method on the FirebaseUser object after the email verification is complete. Try the following code after email verification done:

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.

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.

Source: firebase_auth package

  • Related