问题
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