CodexBloom - Programming Q&A Platform

GCP Firestore Rules Not Enforcing Access Control as Expected with Flutter App

👀 Views: 51 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-05
gcp firestore flutter security-rules Dart

I need some guidance on I'm working on a personal project and I'm working on a personal project and I'm working on a personal project and I'm working on a Flutter application that uses Google Cloud Firestore for data storage... I've set up Firestore with security rules to restrict access based on user authentication status, but I'm working with issues where the rules don't seem to be enforcing the expected access controls. Just to give you a brief overview, here are my Firestore security rules: ```plaintext service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } match /publicData/{docId} { allow read: if true; allow write: if request.auth != null; } } } ``` The intention here is that a user should only be able to read and write their own user document, while authenticated users should have write access to the `publicData` collection, but read access is open to everyone. However, when I try to access a user document using the `Firestore.instance.collection('users').doc(userId).get()` method in Flutter, I'm getting `PERMISSION_DENIED` errors for authenticated users who are querying their own document. I've checked the authentication state and it's correct. The `userId` being passed matches the authenticated user's ID. Here's the relevant Flutter code: ```dart final FirebaseAuth auth = FirebaseAuth.instance; User? user = auth.currentUser; if (user != null) { String userId = user.uid; DocumentSnapshot userDoc = await FirebaseFirestore.instance.collection('users').doc(userId).get(); print(userDoc.data()); } else { print('User is not authenticated'); } ``` I've also tried adding logging in my Firestore rules to see if the request is reaching the rules correctly: ```plaintext allow read: if request.auth != null && request.auth.uid == userId || request.auth.uid == 'testUserId'; ``` This allowed access for a specific user (hardcoded) but didn't work for others. I've confirmed that the user is logged in and the `userId` is accurate; yet, the security rules aren't behaving as expected. I've also cleared the Firestore cache. Could there be something wrong with the way Firestore is set up in my project? Or is there a specific best practice for configuring access rules that I might be missing? Any insights would be greatly appreciated! What's the best practice here? I'd be grateful for any help. For reference, this is a production desktop app. I'm open to any suggestions. What's the best practice here? This is part of a larger microservice I'm building. Cheers for any assistance!