Reputation: 849
I'm using the following Firebase rules:
service cloud.firestore {
match /databases/{database}/documents {
function signedIn() {
return request.auth.uid != null;
}
match /exampleCollectionName/{exampleDocumentName} {
allow get: if signedIn();
allow write, list: if false;
}
}
}
I want to block get requests for users which are not logged in, and allow it for all the others (including those logged in as anonymous).
This is my dart code, using the Firebase Flutter plugins:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
final FirebaseApp app = await FirebaseApp.configure(
name: 'firestoreDatabaseExample',
options: const FirebaseOptions(
googleAppID: 'xxxxxxxx',
apiKey: 'yyyyyyyy',
projectID: 'zzzzzzzz',
),
);
Firestore firestore = Firestore(app: app);
await firestore.settings(timestampsInSnapshotsEnabled: true);
final FirebaseAuth _auth = FirebaseAuth.instance;
await _auth.signOut();
FirebaseUser firebaseUser = await _auth.signInAnonymously();
assert(firebaseUser != null);
assert(firebaseUser.isAnonymous);
assert(!firebaseUser.isEmailVerified);
assert(await firebaseUser.getIdToken() != null);
final FirebaseUser currentUser = await _auth.currentUser();
assert(firebaseUser.uid == currentUser.uid);
DocumentReference docRef =
firestore.collection('exampleCollectionName').document('exampleDocumentName');
await docRef.get().then((documentSnaphot) {
if (documentSnaphot.exists) print('IS WORKING!');
}, onError: (error) {
print(error);
});
}
As you can see above, I log in as anonymous and try to get a document. However, the code returns:
"PlatformException(Error performing get, PERMISSION_DENIED: Missing or insufficient permissions., null)"
Please help, what am I doing wrong?
Upvotes: 2
Views: 837
Reputation: 30879
You have to do:
final FirebaseAuth _auth = FirebaseAuth.from(app);
Otherwise you would be signing in to the "default" app configured by the google-services.json
configuration file.
Upvotes: 3