为什么这些Firestore规则不能与Flutter Firebase插件一起使用?

时间:2018-11-20 15:05:52

标签: firebase plugins firebase-authentication flutter google-cloud-firestore

我正在使用以下Firebase规则:

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;
        }
    }
}

我想阻止未登录用户的获取请求,并允许所有其他用户访问  (包括以匿名身份登录的用户)。

这是我使用Firebase Flutter插件的dart代码:

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);
  });
}

正如您在上面看到的那样,我以匿名身份登录并尝试获取文档。但是,代码返回:

"PlatformException(Error performing get, PERMISSION_DENIED: Missing or insufficient permissions., null)"

请帮助,我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您必须这样做:

final FirebaseAuth _auth = FirebaseAuth.from(app);

否则,您将登录由google-services.json配置文件配置的“默认”应用。