首页 > 解决方案 > 如何为创建操作设置 Firestore 安全规则

问题描述

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

用户需要注册才能使用我的应用程序,我会将一些用户数据保存user_profile在 Firestore 的集合中。由于将向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,
        })

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

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

标签: firebaseflutterfirebase-authentication

解决方案


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

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

推荐阅读