Ajoy Das Ajoy Das - 2 months ago 59
Android Question

Firebase Error: permission denied for Authenticated user

I need to have access of my "myapp.firebase.io/events" node's access to any authenticated users(authenticated by firebase auth) only. My rule is-

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


And my activity is:

public class NotificationActivity extends AppCompatActivity {
TextView message,header;
private Toolbar mToolbar;
String from;
private Firebase ref;
private FragmentDrawerNotification mDrawerFragment;
private FirebaseAuth mAuth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);

mAuth = FirebaseAuth.getInstance();

message = (TextView) findViewById(R.id.tMessage);
header = (TextView) findViewById(R.id.tHeader);

from=getIntent().getExtras().getString("From");
if(from.equals("Events"))
{
header.setText("Events: ");
message.setText("");
System.out.println(mAuth.getCurrentUser().getEmail());
//System.out.println("Events Auth"+ref.getAuth());
ref = new Firebase("https://myapp.firebaseio.com/events");

ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data =dataSnapshot.getValue(String.class);
message.setText(data);
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}
});

}
}


Here
System.out.println(mAuth.getCurrentUser().getEmail());

is returning the logged in user's email correctly but
ref.getAuth()

is returning null;
So,logged in users can't access the data and getting "Firebase Error: permission denied "
Here "events" is my key and "Today has an event" is my value.

If I use

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


I can access it, but I need to secure the database with authenticated users.

Answer

You seem to be mixing usage of legacy Firebase with new Firebase APIs.

//legacy: com.firebase:firebase-client-android:2.5.2+
ref = new Firebase("https://myapp.firebaseio.com/events"); 

//com.google.firebase:firebase-auth:9.4.0
mAuth = FirebaseAuth.getInstance();

Is your project in console.firebase.google.com console? If that is the case, please remove this dependency com.firebase:firebase-client-android:2.5.2+, include com.google.firebase:firebase-database:9.4.0 and follow this guide on how to get a database reference using the new Firebase APIs:

    //com.google.firebase:firebase-database:9.4.0
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = database.getReference("message");

I am assuming you have properly implemented Firebase Auth already as it seems you have an authenticated user.

Comments