【问题标题】:How to set Firestore security rules for create operation如何为创建操作设置 Firestore 安全规则
【发布时间】:2020-12-09 19:48:33
【问题描述】:

我正在用 Flutter 开发一个移动应用程序,并使用 Firebase 作为后端。

用户需要注册才能使用我的应用,我会将一些用户数据保存在 Firestore 的 user_profile 集合中。 由于user_profile集合中会添加一个新文档,不知道用户第一次注册时应该如何设置新文档的安全规则。

以下是我在注册过程中发生的情况:

// Step 1:  Register user with email and password
FirebaseAuth _auth = FirebaseAuth.instance;
await _auth.createUserWithEmailAndPassword(email: email, password: password);

// Step 2: save user data in user_profile collection
FirebaseFirestore.instance
        .collection('user_profile')
        .doc(user.uid)
        .set({
          'uid': user.uid,
          'email': email,
          'name': name,
          'date': DateTime.now,
        })

由于我在调用createUserWithEmailAndPassword(..)函数完成后将用户数据保存在user_profile集合中(意味着用户现在已通过身份验证),因此在Firebase中定义创建操作的安全规则是否安全如下?或者我应该以不同的方式设置它以使其以正确的方式安全?

// Rules for User Profile data
match /user_profile/{any} { 
  // Applies to writes to non-existent documents
  allow create: if request.auth != null; 
}

【问题讨论】:

    标签: firebase flutter firebase-authentication


    【解决方案1】:

    根据我的经验,这应该没问题,但您可以另外检查文档中包含的 uid 是否对应于经过身份验证的用户。

    allow create: if request.auth != null && 
        request.auth.uid == request.resource.data.uid;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      • 2019-09-20
      相关资源
      最近更新 更多