我在下面有以下基本安全规则(任何人都可以阅读公共数据库中的帖子,并可以将自己的信息读/写到他们的帐户中)。
我想放置一个数据库规则,允许特定的UID(例如:cvFcflWuO3XCU8OtRoEkW9p2cXw1
)读/写访问/users/
下的所有信息,这是一个允许访问的特定UID的通配符规则/users/
{
"rules": {
"public":
{
".read": true,
".write": false
},
"users": {
"$uid":
{
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
执行如下例所示的简单编辑不起作用。
".write": "'cvFcflWuO3XCU8OtRoEkW9p2cXw1' === auth.uid",
答案 0 :(得分:0)
我再次尝试了我的解决方案并且工作正常。
以下是任何想要做我所做的事情的人的规则参考。 (这只提供读取权限,但您可以添加另一行进行写入。)
{
"rules": {
"public":
{
".read": true,
".write": false
},
"users": {
".read": "'cvFcflWuO3XCU8OtRoEkW9p2cXw1' === auth.uid",
"$uid":
{
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
答案 1 :(得分:0)
根据documentation,推荐的方法是这样的:
{
"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'"
}
}
}
然后,在服务器上初始化FirebaseApp对象时,使用databaseAuthVariableOverride参数覆盖数据库规则使用的auth对象。在此自定义身份验证对象中,将uid字段设置为您在安全规则中用于表示服务的标识符。
// 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);
}
});