31

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?

koceeng
  • 2,169
  • 3
  • 16
  • 37
Nzadibe
  • 598
  • 2
  • 11
  • 28
  • 1
    There is not much we can say aside from what the error message already says: you're trying to read data that you don't have access to. To allow us to be more helpful, share the *minimal* JSON and security rules that will trigger this error. – Frank van Puffelen Dec 03 '16 at 04:36

8 Answers8

43

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"
  }
}
abhishesh
  • 3,246
  • 18
  • 20
  • Thanks a lot. The problem wasn't in the rules section but am glad you responded. Thanks everyone. – Nzadibe Dec 17 '16 at 08:24
  • 2
    Your security rules are defined as public, so anyone can steal, modify or delete data in your database I am getting the above warning by using that rules. – Shubham Garg Jul 13 '21 at 04:56
18

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.

mcfly
  • 774
  • 1
  • 8
  • 18
10

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.)

Lucy
  • 436
  • 5
  • 8
10

Do some changes on firebase database.

  1. go to firebase -> Database -> rules

screenshot

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

}
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
HandyPawan
  • 1,018
  • 1
  • 11
  • 16
4

Most answers are simply suggesting making the database access to anyone to read and edit. This may be acceptable for rough testing, but certainly not for anything serious.

Google Firebase allows configuration to allow and deny access. Read the official documentation here: https://firebase.google.com/docs/rules/basics#realtime-database
(Make sure to select the right type of Firebase database)

For anything requiring authentication, you will need to set up Firebase auth: https://firebase.google.com/docs/auth

Here are some basic examples:

No access (default)

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

Authenticated Users Only

{
  "rules": {
    ".read": "auth.uid != null",
    ".write": "auth.uid != null"
  }
}

Read Public, Write by Owner Only

{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data

  "rules": {
    "some_path": {
      "$uid": {
        ".read": true,
        // or ".read": "auth.uid != null" for only authenticated users
        ".write": "auth.uid == $uid"
      }
    }
  }
}
jleung51
  • 45
  • 1
  • 2
3

Please try to change your firebase rules like below I faced this problem previously. My problem was in database rules:

{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}
Francis Bacon
  • 4,080
  • 1
  • 37
  • 48
Tanjim ahmed
  • 473
  • 4
  • 15
1

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

1

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

Firebase Console -> Database(develop) -> RULES

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

if you are using the old version add the following rule,

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

Screenshot

Codemaker2015
  • 12,190
  • 6
  • 97
  • 81