[英]Firebase security rules not works
I am using Firebase Authentification in an Web application, and I am using Phone Number authentification as an option to sign in the application. 我在Web应用程序中使用Firebase身份验证,并且在使用电话号码身份验证作为登录应用程序的选项。
function saveUser(fname) {
var user = firebase.auth().currentUser;
var newUserRef = firebase.database().ref('users/' + user.uid);
newUserRef.set({
fname: fname
});
}
Under the following database rules: 根据以下数据库规则:
{
"rules" : {
".read" : false,
".write" : false,
// only authenticated users can write
"users": {
".read": "auth != null",
"$user_id": {
"fname": {
".read": "auth != null",
".write": "auth != null",
".validate": "newData.isString() && newData.val().matches(/^[A-Z]{3,}$/)"
},
}
}
}
}
However, I keep getting the error: 但是,我不断收到错误:
FIREBASE WARNING: set at /users/ypGXpJRM1wdMOuOMf8F7quLnJ073 failed: permission_denied
FIREBASE警告:设置为/ users / ypGXpJRM1wdMOuOMf8F7quLnJ073失败:Permission_denied
Is there a way to avoid this error without changing the rules? 有没有办法在不更改规则的情况下避免此错误?
The first level where your rules allow writing is in /users/$uid/fname
. 您的规则允许写入的第一级位于
/users/$uid/fname
。 But your code tries to write to /users/$uid
. 但是您的代码尝试写入
/users/$uid
。 Since you don't have write permission there, the database rejects the write operation. 由于您那里没有写许可权,因此数据库拒绝写操作。
You have two options to solve this: allow writes to /users/$uid
, or write to /users/$uid/fname
. 您可以通过以下两种方法解决此问题:允许写入
/users/$uid
或写入/users/$uid/fname
。
/users/$uid
/users/$uid
To allow writes to /users/$uid
change your rules to: 要允许写入
/users/$uid
请将规则更改为:
"users": {
".read": "auth != null",
"$user_id": {
".write": "auth != null",
"fname": {
".read": "auth != null",
In fact, you'll likely want to ensure a user can only write their own node, which you do with: 实际上,您可能希望确保用户只能编写自己的节点,您可以这样做:
"users": {
".read": "auth != null",
"$user_id": {
".write": "auth.uid === $uid",
"fname": {
".read": "auth != null",
/users/$uid/fname
/users/$uid/fname
Your current write code tries to write to a place where you don't have permission. 您当前的写代码试图写到您没有权限的地方。 Since you are only writing the
fname
, you can also write to that specific location to get rid of the error: 由于您只写
fname
,因此您也可以写到该特定位置以消除错误:
var newUserRef = firebase.database().ref('users/' + user.uid);
newUserRef.child('fname').set(fname);
Given the data structure I'd probably go for modifying the security rules. 给定数据结构,我可能会去修改安全规则。
These rules are blocking all access: 这些规则阻止了所有访问:
".read" : false,
".write" : false,
You can easily test your db security rules in Firebase database rule simulator tool. 您可以在Firebase数据库规则模拟器工具中轻松测试数据库安全规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.