I can't add a comment in firebase when I am authentified.
There is my rules.
{
"rules": {
".read": true,
".write": "auth != null"
}
}
My activity where I test if user is not null before push in firebase.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String baseUrl = "url";
final Firebase fb = new Firebase(baseUrl+"/comments");
final EditText et = (EditText) findViewById(R.id.comment);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Button btn = (Button) findViewById(R.id.send);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(user != null)
fb.push().child("comment").setValue(et.getText().toString());
}
});
}
}
Error I get in log
W/RepoOperation: setValue at /comments/-L0shVMfCJWab7_5ltnO/comment failed: FirebaseError: Permission denied
When I change the rule of write to true, it work.
I resolve the problem, instead use Firebase Instance I use DatabaseReference.
Here is the code
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String baseUrl = "https://tpdevproject.firebaseio.com/";
final DatabaseReference fb = FirebaseDatabase.getInstance().getReference("comments");
final EditText et = (EditText) findViewById(R.id.comment);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
Button btn = (Button) findViewById(R.id.send);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(user != null)
fb.push().child("comment").setValue(et.getText().toString());
}
});
}
}
You need to specify both rules are true in firebase console-:
{
"rules": {
".read": true,
".write": true,
}
}
Try this:
{
"rules": {
".read": true,
".write": "auth !== null"
}
}
Note the !==
in the write rule, with two equals signs instead of one.
This answer is based on some examples in the Firebase documentation on User Based Security .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.