【问题标题】:Problem with Firebase database rule ("Read" denied; Values get deleted automatically)Firebase 数据库规则问题(“读取”被拒绝;值被自动删除)
【发布时间】:2020-02-11 15:30:00
【问题描述】:

这是我的数据库规则:

{
  "rules": {
    "Users' Input History": {
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid"
      }    
  },

    "Users' Vocabulary List": {
      "$uid": {
        ".read": "auth.uid == $uid",
        ".write": "auth.uid == $uid"
      }
    }
  }
}

如您所见,我正在尝试向具有经过身份验证的 uid(用户)的用户授予读写访问权限。每个用户在“$uid”节点下只能看到自己创建的值,看不到其他用户提交的值。但是,在模拟时,出现错误消息:“读取”被拒绝。下面是我运行模拟时的截图:

下面是可能的数据库节点结构:

{
  "Users' Input History" : {
    "TdtIwvAPewRr1l9HY67PfkLBPbn2" : {
      "-M-eylUaQcCpoyTLwbhk" : "fate"
    }
  },
  "Users' Vocabulary List" : {
    "TdtIwvAPewRr1l9HY67PfkLBPbn2" : {
      "-M-eyxRLoCpDftWQ4cDn" : "hardliner"
    }
  }
}

请注意,这些值(即“fate”和“hardliner”)是我通过 firebase 控制台手动添加到数据库的,只是为了向您展示我希望我的数据库是什么样的。 实际情况是, 当我通过我的手机应用程序向数据库提交一个值(例如“fate”)时,以下几行确实会出现在数据库中一瞬间,但随后立即被自动删除(或消失):

"Users' Input History" : {
    "TdtIwvAPewRr1l9HY67PfkLBPbn2" : {
      "-M-eylUaQcCpoyTLwbhk" : "fate"
    }
  }

当我提交值“强硬派”时也是如此。 所以事实证明,给定当前的数据库规则,新值会在我的数据库中出现然后很快消失,这使得我的数据库规则毫无意义。


这里是用于验证和将值推送到数据库的代码。

我的登录活动:

        @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_google_sign_in);

                (some uncritical codes omitted here)


                GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestIdToken(getString(R.string.default_web_client_id))
                        .requestEmail()
                        .build();

                mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

                mAuth = FirebaseAuth.getInstance();
            }


            @Override
            public void onStart() {
                super.onStart();
                FirebaseUser currentUser = mAuth.getCurrentUser();
                updateUI(currentUser);
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);

        GoogleSignInApi.getSignInIntent(...);
                if (requestCode == RC_SIGN_IN) {
                    Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
                    try {
                        // Google Sign In was successful, authenticate with Firebase
                        GoogleSignInAccount account = task.getResult(ApiException.class);
                        firebaseAuthWithGoogle(account);

    //The mDetailTextView will display the user's unique uid and the become the variable "username" which will later be used to push values into the database.                            
    username = mDetailTextView.getText().toString();

                    } catch (ApiException e) {
                        Log.w(TAG, "Google sign in failed", e);
                        updateUI(null);
                    }
                }
            }


            private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
                Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
                showProgressBar();

                AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
                mAuth.signInWithCredential(credential)
                        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) {
                                    Log.d(TAG, "signInWithCredential:success");
                                    FirebaseUser user = mAuth.getCurrentUser();
                                    updateUI(user);
                                } else {
                                    Log.w(TAG, "signInWithCredential:failure", task.getException());
                                    Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
                                    updateUI(null);
                                }

                                hideProgressBar();
                            }
                        });
            }

            private void signIn() {
                Intent signInIntent = mGoogleSignInClient.getSignInIntent();
                startActivityForResult(signInIntent, RC_SIGN_IN);
            }


private void updateUI(FirebaseUser user) {
        if (user != null) {
            mDetailTextView.setText(getString(R.string.Firebase_status_fmt, user.getUid()));
        } else {
            mDetailTextView.setText(null);
        }
    }

我将值推送到数据库的活动:

public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
    public static DatabaseReference mChildReferenceForInputHistory = mRootReference.child("Users' Input History");
    public static DatabaseReference mChildReferenceForVocabularyList = mRootReference.child("Users' Vocabulary List");

searchKeyword = wordInputView.getText().toString();


Query query = mChildReferenceForInputHistory.child(username).orderByValue().equalTo(searchKeyword);

                query.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                            snapshot.getRef().setValue(null);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        throw databaseError.toException();
                    }
                });

                mChildReferenceForInputHistory.child(username).push().setValue(searchKeyword);



mChildReferenceForInputHistory.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildKey) {

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    String value = snapshot.getValue(String.class);
                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

我已尽我所能解释这种情况,但我完全不知道如何开始查明原因并解决问题。有人可以帮忙吗?

【问题讨论】:

  • “但是,在模拟时,出现错误提示:“读取”被拒绝。”请编辑您的问题以显示您运行的模拟的屏幕截图。您读取的路径和您指定的身份验证详细信息尤其重要,因此请确保它们在屏幕截图中可见。
  • 您好,谢谢,弗兰克。我添加了屏幕截图,我想这就是你的意思?
  • Query query = mChildReferenceForInputHistory.child(username) 这看起来很奇怪,因为您的数据库似乎使用 UID 来识别(和保护)用户数据,而在代码中您使用用户在文本框中输入的值。
  • 数据库对每个用户名使用 uid。我更新了我的帖子并添加了 updateUI() 辅助方法。注意这两行: (1) mDetailTextView.setText(getString(R.string.Firebase_status_fmt, user.getUid())); (2) 用户名​​ = mDetailTextView.getText().toString(); . getUid() 将获取用户的 uid,这将成为字符串“用户名”。至于这一行:searchKeyword = wordInputView.getText().toString(); ,“wordInputView”是用户输入单词的EditTextview,该单词将成为“$uid”节点下作为值推送到数据库的String“searchKeyword”。
  • 其实在写这篇文章之前,我尝试使用默认的数据库规则,即 { "rules": { ".read": true, ".write": true } } ,同时使用您现在在我的帖子中看到的当前登录和推送值代码。一切正常,这意味着没有出现消失问题,直到我开始将数据库规则更改为您在我的帖子中看到的屏幕截图。所以我认为我的代码没有问题,也许是因为我写错了规则。也许我的代码有问题,我还不知道。

标签: android authentication firebase-realtime-database firebase-security rules


【解决方案1】:

您正在尝试读取数据库的根目录。这意味着 Firebase 会检查当前用户是否具有 root 的读取权限。由于您没有登录,因此该用户只有在您的规则如下所示时才具有读取权限:

{
  "rules": {
    ".read": true
  }
}

而且由于你没有这样的规则,读操作被拒绝了。


如果您希望能够在模拟器中读取数据,请务必切换“已验证”按钮,并为用户提供 JSON 中存在的 UID(例如 TdtIwvAPewRr1l9HY67PfkLBPbn2)。

但即便如此,您也无法从根目录读取。您没有授予任何人 .read 对 root 的权限,默认情况下不允许所有读取。

这里要记住的重要一点是,规则实际上并不过滤数据。它们仅由数据库服务器用于检查是否允许读取操作。所以如果你尝试从 root 读取,并且没有 root 的读取权限,读取操作会被完全拒绝。

由于您只允许用户在您的安全规则中读取他们自己的节点,因此您应该在模拟器中读取该确切路径。因此,如果您将认证用户设置为TdtIwvAPewRr1l9HY67PfkLBPbn2,那么读取路径将类似于:

/Users' Input History/TdtIwvAPewRr1l9HY67PfkLBPbn2

这也意味着,如果您想同时读取特定用户的Users' Input HistoryUsers' Vocabulary List,则需要两次读取操作。

【讨论】:

  • 这解释了“读取被拒绝”的问题。是不是也解决了“自动消失”的问题?
  • 通常,如果您在客户端上短暂看到写入数据的数据,然后它消失了,这意味着安全规则拒绝了该写入操作。为了能够更好地帮助解决这些问题,请分享[任何人都可以运行以重现问题的最小、完整/独立代码](;stackoverflow.com/help/mcv)。这是让我们为您提供帮助的最有效方式,因为现在看来我试图帮助您解决您的模拟器问题并不是您真正想要的。
  • 感谢弗兰克的提示。我用一些用于登录和推送值的代码更新了我的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 2020-04-13
相关资源
最近更新 更多