Firebase 存储安全规则拒绝读取权限,即使"allow read: if true"



我可能错过了一些简单的东西。我已经被这个问题困扰了一段时间,它很关键。如有任何帮助,不胜感激。

我有一个firestore存储数据库,其规则允许每个人读取(查看)图像。

rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /images/{userId} {
allow read: if true;
allow write: if request.auth != null && request.auth.uid == userId;
}
match /videos/{userId} {
allow read: if true
allow write: if request.auth != null && request.auth.uid == userId;
}
}
}

然而,当我刷新一个特定的页面时,我得到一个:

Uncaught (in promise) FirebaseError: Firebase Storage: User does not have permission to access 'images/BJBAPfJMTCOq9OypfdkZ9z1NtQ93'. (storage/unauthorized)

列出属于特定用户的所有图像的代码:

export default function MultiMedia({ handleUser }) {
const imageListRef = useRef(ref(storage, `images/${handleUser}`));
const [imageList, setImageList] = useState([]);
useEffect(() => {
listAll(imageListRef.current).then((response) => {
response.items.forEach((item) => {
getDownloadURL(item).then((url) => {
setImageList((prev) => [...prev, url]);
});
});
});
}, []);
return...

令人困惑的是,图像确实在不同的页面上呈现,主页从firestore数据库中提取图像url和uid作为字段,以及其他字段。

export default function ImageGallery() {
const [imageData, setImageData] = useState([]);
useEffect(() => {
async function reloadHome() {
try {
const querySnapshot = await getDocs(collection(db, "images"));
querySnapshot.forEach((doc) => {
setImageData((prevValue) => {
return [
...prevValue,
{ imageURL: doc.data().imageURL, user: doc.data().user },
];
});
});
} catch (error) {
console.log(error);
}
}
reloadHome();
}, []);

Firestore security for images文件夹:

rules_version = '2';
service cloud.firestore {
match /images/{image} {
allow read: if true;
allow create: if isLoggedIn();
allow update, delete: if isLoggedIn() && request.auth.uid == resource.data.user;
}
}

我希望防止用户看到从Firebase存储中提取的用户配置文件中的图像的存储安全规则应该与防止同一用户看到存储在Firebase数据库中的下载URL的同一图像的规则相同。

由于您在users/{userId}上使用listAll(),我假设在该前缀下有多个文件,而不是单个对象。在这种情况下,您必须为该前缀内的对象指定规则,并且只指定您现在正在执行的路径。例如,您当前的规则将允许读取对象images/user1.png。尝试使用递归通配符,如下所示:

match /images/{userId}/{file=**} {
allow read: if true;
allow write: if request.auth != null && request.auth.uid == userId;
}

另外,不用在循环的每次迭代中更新状态,你可以像这样只更新一次:

useEffect(() => {
listAll(imageListRef.current).then(async (response) => {
const promises = response.items.map((item) => getDownloadURL(item));
const urls = await Promise.all(promises);
setImageList(urls);
})
}, []);

如果你设置了allow read: if true;如果您在尝试从firebase存储中读取时仍然看到读取权限错误,您可以检查以下几件事:

  1. 确保您已经过身份验证:如果您的firebase存储安全规则要求对访问某些数据进行身份验证,那么在尝试访问该数据之前确保您已经过身份验证是很重要的。您可以通过调用firebase.auth()来检查您是否通过了身份验证。

  2. 检查您试图访问的firebase存储桶:如果您有多个firebase存储桶,请确保您在代码中使用正确的桶名。您可以通过转到firebase控制台,导航到您的项目,并选择左侧菜单中的"storage"选项来检查firebase存储桶的名称。

  3. 检查你的代码是否有错误:确保你的客户端javascript代码没有产生任何可能阻止你的firebase存储规则正常工作的错误。你可以使用浏览器的开发工具来检查代码中的错误。

  4. 检查firebase存储是否配置为使用自定义域名:如果您在firebase存储中使用自定义域名,请确保您的dns记录设置正确并指向正确的firebase存储桶。

  5. 尝试清除您的缓存和cookie:如果您仍然有firebase存储访问问题,尝试清除您的web浏览器缓存和cookie。

如果这些解决方案都不起作用,您可能需要检查您的firebase

最新更新