【发布时间】: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