Firestore身份验证失败

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Firestore身份验证失败相关的知识,希望对你有一定的参考价值。

问题

我正在构建一个使用flutter存储数据的firestore应用。我已经无法在启用身份验证的情况下将数据写入firestore,当禁用身份验证时它可以工作。我已经对所有Firebase进行了颤振设置步骤两次,但都无济于事。逐步执行代码时,我可以看到与Google进行Firebase身份验证工作正常,并且正在返回ID令牌和当前用户,因此此处的身份验证过程不是问题。

当呼叫firestore时出现此异常

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

代码

[flutter_bloc状态管理很难显示所有相关代码。这是登录代码和firestore代码。

使用Google登录

  @override
  Stream<AuthStates> mapEventToState(AuthEvents event) async* {
    if (event is SignInWithGooglePressed) {
      yield await _signInWithGoogle();
    }
    ...
  }

  Future<AuthStates> _signInWithGoogle() async {
    final GoogleSignInAccount googleUser = await  GoogleSignIn().signIn();
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    return await _signInWithCredential(credential);
  }

  Future<AuthStates> _signInWithCredential(AuthCredential credential) async {
    var failedMessage = '';
    try {
      final AuthResult result = await _auth.signInWithCredential(credential);
      return await _getResult(result, failedMessage);
    } on PlatformException catch (e) {
      return AuthStates.signInFailed(e.message);
    }
  }

  Future<AuthStates> _getResult(AuthResult result, String failedMessage) async {
    final FirebaseUser user = result.user;

    if (!user.isAnonymous && await user.getIdToken() != null) {
      final FirebaseUser currentUser = await _auth.currentUser();
      if (currentUser.email == user.email) {
        return AuthStates.signedIn();
      }
    }

    return AuthStates.signInFailed(failedMessage);
  }

Firestore存储库

@Named('firebaseRepository')
@RegisterAs(Repository)
class FirebaseRepository extends Repository {
  final Firestore _firestore;

  FirebaseRepository._create(this._firestore);

  static Future<FirebaseRepository> create() async {
    final FirebaseApp app = await FirebaseApp.configure(
      name: 'myApp',
      options: Platform.isios
          ? const FirebaseOptions(
              googleAppID: 'myAppID',
              apiKey: 'myApiKey',
              gcmSenderID: 'senderId',
              projectID: 'myApp',
            )
          : const FirebaseOptions(
              googleAppID: 'myAppID',
              apiKey: 'myApiKey',
              gcmSenderID: 'senderId',
              projectID: 'myApp',
            ),
    );

    return FirebaseRepository._create(Firestore(app: app));
  }

  @override
  void addAddress(User user, Address address) async {
    var userId = user.emailAddress.value.getOrElse(() => '');
    var addressMap = {
      'user_id': userId,
      'address_line_1': address.addressLine1.value.getOrElse(() => ''),
      'address_line_2': address.addressLine2.value.getOrElse(() => ''),
      'area': address.area.value.getOrElse(() => ''),
      'province': address.province.value.getOrElse(() => ''),
      'country': address.country.value.getOrElse(() => ''),
      'code': address.code.value.getOrElse(() => ''),
    };

    DocumentReference addresses =
        _firestore.collection('addresses').document(userId);
    await addresses
        .setData(addressMap)
        .whenComplete(() => {})
        .catchError((onError) {
      print('error : $onError');
    });
  }
}

Dependencies

  firebase_core: ^0.4.0+9
  firebase_auth: 0.16.0
  cloud_firestore: 0.13.5

  google_sign_in: 4.4.4

Firebase规则

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

我想念什么?

是否有任何明显的证据表明我失踪了?我以为我可能会缺少firestore初始化的步骤,该步骤需要向api提供auth令牌,但我不确定吗?我在普通的android系统中做了很多次,没有任何问题。

答案

更新您的规则并尝试。这是我唯一的猜测,为什么会发生

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

Ps。代码在注释中看起来不太好,所以我将其发布为答案

以上是关于Firestore身份验证失败的主要内容,如果未能解决你的问题,请参考以下文章

具有身份验证的Cloud Firestore

试图从 localhost 服务器连接 mLAB DB?身份验证失败

Flutter:使用从 Firebase 身份验证创建的帐户在 Firestore 中创建用户

Firestore 云功能 apollo graphql 身份验证

验证现有身份验证用户的电子邮件后更新 Firestore 文档?

Flutter:Firebase 身份验证和 Firestore 快照流