目标:允许经过身份验证的用户上传个人资料照片(并将其与该用户关联)。
注意:我关注了用户文档:https://firebase.google.com/docs/storage/security/user-security
问题:我收到错误:
StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
StorageException: The server has terminated the upload session
java.io.IOException: The server has terminated the upload session
测试完成: 我首先得到了以下规则,能够允许经过身份验证的用户上传照片(但它与该用户无关): Authenticated Users
我将规则更改为以下内容,将图片与用户ID相关联: Associate Image to UserID
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if request.auth != null;
}
match /images {
// Only an individual user can write to "their" images
match /{userId}/{imageId} {
allow write: if request.auth.uid == userId;
}
}
}
}
使用应该将照片与用户ID相关联的新规则,我收到有关没有权限的存储异常错误。
如果重要的话,这是我的存储参考:
storage = FirebaseStorage.getInstance();
storageReference = storage.getReferenceFromUrl("gs://app-name.appspot.com").child("20170702_174811.jpeg"); //was PNG
和
public void handleChooseImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE); //then goes to onActivityResult
}
除了文档,我还尝试在这个主题上观看尽可能多的YouTube视频,但似乎遗漏了一些东西。有人可以指出我正确的方向吗?
答案 0 :(得分:0)
这里有两个(可能是三个)问题:
1:您对所有需要身份验证的文件({allPaths=**}
)都有规则,而第二个更具体的文件需要每用户身份验证。您可能只想要:
service firebase.storage {
match /b/{bucket}/o {
match /images/{userId}/{imageId} {
allow write: if request.auth.uid == userId;
}
}
}
2:您指向的是单个文件名,而不是/images/{userId}/{imageId}
路径。相反,做:
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
String imageId = "myFile.png" // or whatever you want to call it
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference ref = storage.getReference()
.child("images")
.child(userId)
.child(imageId);
3:如果您尚未使用Firebase Auth并与提供商签到。