安卓Firebase中setValue()方法权限被拒绝

5
这是 Firebase 中规则的定义方式:

{
"rules": {
 "users": {
  ".read": true,
    "$user_id": {
     ".write": "auth.uid === $user_id",
     ".read" : true
  }}}}

我已经成功地使用setValue()在我的注册活动中编写了新用户信息,就像下面这样,并且还使用push().setValue()添加了新评论。每次我都没有认证问题。新用户被直接写入http://DB/users/,而评论被添加得非常深入。
这是一个代码片段,我的代码会打印出“数据无法保存”的日志,每次都是如此。
AuthData authData = newRef.getAuth();

    if (authData != null) {
        Log.v(LOG_TAG, "Auth as " + authData.getUid());
        Map<String, Object> newEntry = new HashMap<String, Object>();
        newEntry.put("Name", name);
        newEntry.put("Description", desc);
        newEntry.put("DueDate", date);
        newEntry.put("Status", 0);

        newRef.setValue(newEntry, new Firebase.CompletionListener() {
            @Override
            public void onComplete(FirebaseError firebaseError, Firebase firebase) {
                if (firebaseError != null) {
                    Log.v(LOG_TAG, "Data could not be saved. " + firebaseError.getMessage()); //Hits here every time.
                } else {
                    Log.v(LOG_TAG, "Data saved successfully. Finishing activity...");
                    finish();
                }
            }
        });
        ;
    }
    else{
        Log.v(LOG_TAG, "No authdata");
    }

希望我提供的信息足够了解决问题,我猜测问题出在安全/规则上,但任何方向/指导都将不胜感激。谢谢。


你使用的Firebase版本是什么?这里有一篇文章描述了在某些条件下调用setValue()方法时抛出“权限被拒绝”错误:http://stackoverflow.com/questions/19817709/firebase-auto-reconnect-on-android。根据被接受的答案,这个问题在1.0.10版本中已经修复了。 - Willis
我在我的依赖项中有以下内容:compile 'com.firebase:firebase-client-android:2.2.3+' - thurst0n
只是想补充一下,我尝试使用updateChildren()代替setValue()作为另一种选择,但返回相同的权限被拒绝。 - thurst0n
啊,对于那些浪费时间的人感到抱歉,我的URL路径不正确。我感觉自己像个白痴。 - thurst0n
感谢 @thurst0n 告诉我们这个修复方法。我会投票关闭,因为这是一个打字错误。 - Frank van Puffelen
好的!我一直盯着那个路径看,但我只检查了结尾而没有检查开头。嘿。 - thurst0n
3个回答

30

我之前卡在一个点上,以下是帮助我的方法。

首先,有两种类型的用户可以从Firebase访问数据库:

  1. 已授权
  2. 未授权

默认情况下,它被设置为未授权,但是他们既没有权限也没有权限,因此最初如果您尝试执行任何操作,您会收到“权限被拒绝”的错误。

如何更改以满足您的要求?

解决方案:

在数据库部分,转到规则选项卡。URL将类似于此,其中包含您的项目名称。
https://console.firebase.google.com/project/project-name/database/rules

您将在此处看到类似于此的内容:

{
  "rules": {
    ".read": "auth != null", //non-authorised users CANT read
    ".write": "auth != null" //non-authorised users CANT write
  }
}

只需更改此内容

{
  "rules": {
    ".read": "auth == null", //even non-authorised users CAN read
    ".write": "auth == null" //even non-authorised users CAN write
  }
}

按照您的需求更改此内容。编码愉快 :)


1
当我打开数据库规则时,我发现以下代码:service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; }}}但是,如果我添加你提到的代码,Firebase 就无法识别它了... 请帮忙解决。 - Abdul Waheed

1

1
对于遇到此问题的人,请不要忘记更改默认提供的Firebase“数据库类型”,应该注意到有2种类型的数据库,一种是Cloud Firestore,另一种是RealTime Database
回答这个问题,确保您正在使用实时数据库:

Change the type of database

然后编辑规则:

Edit your security rules in the section of Database>Rules

显然,这种规则配置只能用于开发环境,不要忘记在生产环境中更改规则。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接