Nzadibe
Nzadibe

Reputation: 638

Android Firebase Database Error: Permission denied

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?

Upvotes: 34

Views: 63085

Answers (8)

jleung51
jleung51

Reputation: 45

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"
      }
    }
  }
}

Upvotes: 4

Tanjim ahmed
Tanjim ahmed

Reputation: 599

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"
  }
}

Upvotes: 3

Codemaker2015
Codemaker2015

Reputation: 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

Upvotes: 1

Kushagar Choudhary
Kushagar Choudhary

Reputation: 11

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

Upvotes: 1

mcfly
mcfly

Reputation: 834

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.

Upvotes: 17

HandyPawan
HandyPawan

Reputation: 1106

Do some changes on firebase database.

  1. go to firebase -> Database -> rules

screenshot

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

}

Upvotes: 10

Lucy
Lucy

Reputation: 436

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

Upvotes: 10

abhishesh
abhishesh

Reputation: 3316

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"
  }
}

Upvotes: 49

Related Questions