Android Firebase Database Error: Permission denied

2020-07-03 06:44发布

问题:

I am working on an android project that requires user email and pwd authentication. The details are stored in the firebase database.The problem occurs whenever I try logging in again with the email and password. In my logcat the error message is:

W/SyncTree: Listen at / failed: DatabaseError: Permission denied

Take a look at my code below:

public class LoginUser extends AppCompatActivity {

private RelativeLayout relativeLayout;

private EditText et_email, et_password;
private Button loginBtn;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private DatabaseReference databaseReference;

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

    mAuth = FirebaseAuth.getInstance();
    databaseReference = FirebaseDatabase.getInstance().getReference();
    databaseReference.keepSynced(true);

    relativeLayout = (RelativeLayout) findViewById(R.id.activity_login_user);

    et_email = (EditText) findViewById(R.id.emailField);
    et_password = (EditText) findViewById(R.id.pwdField);
    loginBtn = (Button) findViewById(R.id.loginBtn);

    loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            initLogin();
        }
    });

    authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() != null){
                initLogin();
            }
            else {
                startActivity(new Intent(LoginUser.this,RegisterFireBase.class));
            }
        }
    };

}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(authStateListener);
}

@Override
protected void onStop() {
    super.onStop();
    if (mAuth != null){
        mAuth.removeAuthStateListener(authStateListener);
    }
}

private void initLogin() {

    String email = et_email.getText().toString().trim();
    String pass = et_password.getText().toString().trim();

    if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(pass)){
        mAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                checkForUser();

            }
        });
    }
    else {
        Toast.makeText(this, "Some fields are empty", Toast.LENGTH_SHORT).show();
    }

}

private void checkForUser() {

    final String userId = mAuth.getCurrentUser().getUid();
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(userId)){

                Intent loginIntent =  new Intent(LoginUser.this, FireProfile.class);
                loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(loginIntent);

                Snackbar.make(relativeLayout,"Log In Successful",Snackbar.LENGTH_LONG).show();

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

}

What could be causing this?

回答1:

Possible reason could be : you dont have read and write access on your database. For enabling read and write access :

Go to firebase console and enable read and write operations on your database.

Firebase Console -> Database(develop) -> RULES

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


回答2:

Go to the Rules tab on your Database console. If you have not explicitly granted .read access to your user then permission will be denied.

This link is excellent in the Firebase doc:

https://firebase.google.com/docs/database/security/securing-data

These two notes on that page are of particular interest:

Note: Access is disallowed by default. If no .write or .read rule is specified at or above a path, access will be denied.

Note: Shallower security rules override rules at deeper paths. Child rules can only grant additional privileges to what parent nodes have already declared. They cannot revoke a read or write privilege.

Review the node where permission is being denied and use the Simulator on the Rules tab in order to test your rules for different user security contexts (non-authenticated, authenticated, etc.)



回答3:

Do not put you app public if this is not needed. As described on google documentation you can do these rules on your firebase > database > rules

// These rules grant access to a node matching the authenticated
// user's ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

or to let only authenticated users

// These rules require authentication
    {
      "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
    }

Letting an app public let anyone write and read your app... i don't think any app should use this like that.



回答4:

Do some changes on firebase database.

  1. go to firebase -> Database -> rules

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

}


回答5:

the problem is that the firebase database has two projects with the same name and one of the project's rules are not even enabled So see on all projects once