Firestore Rules拆分自定义令牌下划线前缀匹配DocumentId的方案问询
解决方案
最优实现:无需修改自定义声明结构,直接用Firestore Rules内置方法完成校验
Firestore Rules提供了列表的any()迭代方法和字符串处理能力,不需要手动写循环,也不用新增冗余字段就能实现你的需求,有两种常用写法可供选择:
写法1:使用split()拆分字符串(可读性更高)
直接按下划线拆分字符串,取第一个元素和组织ID比对即可:
match /databases/{database}/documents { match /organizations/{uid}/repositories/{document=**} { allow read: if request.auth != null && request.auth.token.organizations.any((org) => org.split('_')[0] == uid); } }
写法2:使用正则前缀匹配
如果担心部分特殊场景下拆分逻辑异常,可以用正则匹配前缀:
match /databases/{database}/documents { match /organizations/{uid}/repositories/{document=**} { allow read: if request.auth != null && request.auth.token.organizations.any((org) => org.matches('^' + uid + '_.*')); } }
注意事项
- 两种写法都是Firestore Rules原生支持的语法,没有用到被限制的循环操作
- 前端可以正常从Custom Claims中拿到完整的
ID_项目名字符串,自行拆分得到ID和名称使用,没有冗余存储 - 注意Custom Claims总大小不能超过1000字节,organizations列表不要存储过多条目,避免超出限制导致声明设置失败
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

