Flutter - Your Cloud Firestore database has insecure rules

前端 未结 1 1853
北恋
北恋 2020-12-20 09:13

I have a collection called users where I am checking if new users mobile no is present or not. If It is present then I am performing phone authentication fo

相关标签:
1条回答
  • 2020-12-20 09:52

    You can change your rule adding more security like this:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    

    But, then your app won't be able to read from Firebase, since you are telling that even for read is necessary to be authenticated.

    I solved this allowing users to authenticate anonymously in Firebase. For this go to:

    https://console.firebase.google.com/project/[YOUR-PROJECT]/authentication/providers

    and enable Anonymous method. Remember to change [YOUR-PROJECT] in the URL.

    After this you will only need to add few lines of code in your main screen or whatever you want.

    1) Import the Firebase Auth package:

    import 'package:firebase_auth/firebase_auth.dart';
    

    2) Add the following code at the beginning of your main StatefulWidget:

    final FirebaseAuth firebaseAuth = FirebaseAuth.instance;
        Future<FirebaseUser> signInAnon() async {
            AuthResult result = await firebaseAuth.signInAnonymously();
            FirebaseUser user = result.user;
            print("Signed in: ${user.uid}");
            return user;
        }
        void signOut() {
            firebaseAuth.signOut();
            print('Signed Out!');
        }
    

    3) And now you just have to call the function inside your initState:

    signInAnon().then((FirebaseUser user){
         print('Login success!');
         print('UID: ' + user.uid);
    });
    

    And voilá! Now every user user will authenticate anonymously automatically in your Firebase database. The best part is the user persists in the app until you uninstall it or delete the cache data.

    Here is a video explaining the steps, but using a login screen which I removed for my project and this example: https://www.youtube.com/watch?v=JYCNvWKF7vw

    0 讨论(0)
提交回复
热议问题