我的 Firebase 存储数据库有以下规则:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
allow write: if request.auth.token.role == "admin";
}
}
通过以下代码,我已验证我的 UID 具有管理员角色:
const admin = require('firebase-admin');
const serviceAccount = require('./key-file.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
projectId: "some-project-id",
});
const uid = 'my-uid';
admin.auth().getUser(uid)
.then((userRecord) => {
console.log(userRecord.customClaims);
});
输出示例:
{ role: 'admin' }
但是,当我的客户端(Dart 代码)尝试上传图像时,权限被拒绝。这是我的上传代码:
print('Current UID: ${FirebaseAuth.instance.currentUser?.uid}');
final testFileContent = Uint8List.fromList('This is a test file'.codeUnits);
FirebaseStorage.instance.ref().child('test.txt').putData(testFileContent);
日志:
I/flutter ( 7630): Current UID: X2vSwXi5PIeOWkQOCmXxvzqTPem2
E/StorageException( 7630): StorageException has occurred.
E/StorageException( 7630): User does not have permission to access this object.
有人对如何调试这个有更好的建议吗?
我已经完成了所有通用的事情,例如:
如果我可以在 Firebase 控制台上看到用户的自定义声明,或者使用 Rules Playground 对其进行测试,那就太好了,但这似乎不受支持。
发布问题和答案,以防其他人发现同样的问题。规则在路径上缺少匹配项 - 它们需要如下所示:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} { // You have to specify which path the rules apply to!
allow write: if request.auth.token.role == "admin";
}
}
}
注意 - 向用户添加声明时,即使用以下 Javascript 代码:
const admin = require('firebase-admin');
const serviceAccount = require('./key-file.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
projectId: "some-project-id",
});
admin.auth().setCustomUserClaims("some-user-uid", {"claim1": "value2"});
具有uid
some-user-uid
的人必须注销并重新登录才能使数据库规则生效。