Flutter - Your Cloud Firestore database has insecure rules

回眸只為那壹抹淺笑 提交于 2020-05-24 05:44:06

问题


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 for that user then storing uid as a field in document.

If user is coming for the first time, he is not authenticated and I am performing read operation from users collection. Now every time I am getting Your Cloud Firestore database has insecure rules email from google.

Below is the rule I am using. Please let me know how can I make it secure.

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

回答1:


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



来源:https://stackoverflow.com/questions/60005221/flutter-your-cloud-firestore-database-has-insecure-rules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!