聊天应用Firebase Realtime Database规则校验与修正咨询
Firebase 聊天应用实时数据库规则修正方案
原规则典型问题汇总
- 语法结构错误:规则逻辑表达式需完整包裹在双引号内,原规则将
&&逻辑运算符放在引号外,不符合Firebase规则语法要求 - 路径取值错误:无法直接通过
"$uid/current_page"字符串匹配节点值,需通过data/root等规则内置对象调用child()方法取值 - 拼写失误:
connections节点规则中current_page字段名后多写了空格,无法匹配到实际字段 - 变量未定义:
messages节点直接使用未声明的$uid变量,应取认证用户的唯一标识auth.uid - 规则缺失:
messages节点仅配置了.validate校验,未配置.write权限规则,无法控制写入权限 - 通配符匹配逻辑错误:用
==无法匹配带*的通配符路径,需调用matches()方法做正则匹配 - JSON格式错误:节点间缺少逗号分隔、字符串未正确闭合,注释位置不当会破坏JSON结构
修正后完整规则
{ "rules": { "users": { "$uid": { // 仅允许已认证用户、且当前页面匹配我方站点域名的读写操作 ".read": "auth != null && data.child('current_page').val().matches(/^3w_stringofmywebsite\\/.*/)", ".write": "auth != null && data.child('current_page').val().matches(/^3w_stringofmywebsite\\/.*/)" } }, "connections": { "$uid": { // 仅允许已认证用户、且对应user节点的当前页面匹配我方站点域名的读操作 ".read": "auth != null && root.child('users').child($uid).child('current_page').val().matches(/^3w_stringofmywebsite\\/.*/)" } }, "messages": { // 仅允许已认证用户、且当前登录用户的user节点页面匹配我方站点域名的读操作 ".read" : "auth != null && root.child('users').child(auth.uid).child('current_page').val().matches(/^3w_stringofmywebsite\\/.*/)", // 仅允许已认证用户、且当前登录用户的user节点页面匹配我方站点域名的写入操作 ".write": "auth != null && root.child('users').child(auth.uid).child('current_page').val().matches(/^3w_stringofmywebsite\\/.*/)", // 校验写入的msg字段必须为长度不超过140的字符串 ".validate": "newData.child('msg').isString() && newData.child('msg').val().length <= 140" } } }
额外注意事项
- 规则中
3w_stringofmywebsite请替换为实际的站点域名前缀,正则表达式的特殊字符需要转义 - 写入校验时要用
newData取待写入的数据,不要用data(data是写入前的节点数据) - 生产环境建议进一步收紧权限,比如限制用户只能读写和自己相关的消息、连接数据,避免越权访问
内容的提问来源于stack exchange,提问作者Ta Rik
相关产品推荐
相关产品推荐

