firebase - 如何为创建操作设置 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;
}
解决方案
根据我的经验,这应该没问题,但您可以另外检查文档中包含的 uid 是否对应于经过身份验证的用户。
allow create: if request.auth != null &&
request.auth.uid == request.resource.data.uid;
推荐阅读
- javascript - Javsacript。如何操作对象数组以便将具有相同元素的元素分组?
- python - 从点往四个方向走
- c - 获得纯正弦波的困难(目前获得一个微妙的频率)
- reactjs - 如何将社交媒体图标添加到反应组件?
- database - 当应用程序在发送查询以更新记录后立即断开连接时会发生什么?
- julia - 在 Julia 中获取子数组的索引
- typescript - 如何抽象 Typescript 中的类型交集?
- c++ - 二进制搜索不适用于特定输出
- sql - 如何根据特定条件生成行号?
- java - 我正在尝试通过 mysql 数据库在 jdbc 中使用 GUI 插入值,这给了我以下异常: