As per the documentation, the recommended approach is something like this:
{
"rules": {
"public_resource": {
".read": true,
".write": true
},
"some_resource": {
".read": "auth.uid === 'my-service-worker'",
".write": false
},
"another_resource": {
".read": "auth.uid === 'my-service-worker'",
".write": "auth.uid === 'my-service-worker'"
}
}
}
Then, on your server, when you initialize the FirebaseApp object, use the databaseAuthVariableOverride parameter to override the auth object used by your database rules. In this custom auth object, set the uid field to the identifier you used to represent your service in your Security Rules.
// Fetch the service account key JSON file contents
FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountCredentials.json");
// Initialize the app with a custom auth variable, limiting the server's access
Map<String, Object> auth = new HashMap<String, Object>();
auth.put("uid", "my-service-worker");
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://databaseName.firebaseio.com")
.setDatabaseAuthVariableOverride(auth)
.build();
FirebaseApp.initializeApp(options);
// The app only has access as defined in the Security Rules
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference("/some_resource");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String res = dataSnapshot.getValue();
System.out.println(res);
}
});
"users": {
it should work. If not, can you show the complete rules and the accompanying code that don't work together? – Frank van Puffelen