我一直在嘗試使用 Firebase 代碼在我的 Windows 11 PC 和我的 Firebase 存盤桶之間上傳/下載檔案。一旦我讓它作業,我意識到代碼不包含登錄。由于我使用的是默認的 Cloud Storage 規則,因此我預計我的上傳/下載呼叫會被退回。
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
我清除了瀏覽器快取并退出了 Google 和 Firebase 控制臺,看看是否可以解決問題。它沒有,重啟也沒有。但是后來我發現代碼在完全獨立的機器上運行時出現了預期的錯誤,這讓我松了一口氣。在這種情況下運行我的代碼(現在部署到網路上)產生了預期的錯誤:
“糟糕 - 上傳失敗:錯誤 = FirebaseError:Firebase 存盤:用戶無權訪問 'some-child'。(存盤/未授權)”。
但是問題在我的開發 PC 上仍然存在,所以我的問題是,什么可能使 Firebase 進入繞過云存盤規則的狀態,即使沒有登錄也允許存盤桶訪問?
這是我正在使用的 (firebase v9) 代碼(它允許我將 PC 上的選定檔案上傳到存盤桶中名為“some-child”的檔案,然后將其下載到我的檔案中名為 demo.txt 的檔案中)下載檔案夾)。:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js';
import { getAuth, GoogleAuthProvider, signInWithPopup } from 'https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js';
import { getStorage, ref, uploadBytes, getDownloadURL } from 'https://www.gstatic.com/firebasejs/9.4.0/firebase-storage.js';
const firebaseConfig = {
...
};
const firebaseApp = initializeApp(firebaseConfig);
const provider = new GoogleAuthProvider();
const auth = getAuth();
const storage = getStorage();
const storageRef = ref(storage, 'some-child');
window.onload = function () {
document.getElementById('fileitem').onchange = function () { uploadFile() };
document.getElementById('downloadbutton').onclick = function () { downloadFile() };
}
function uploadFile() {
var file = document.getElementById('fileitem').files[0];
uploadBytes(storageRef, file)
.then((snapshot) => {
alert('Successful upload');
})
.catch((error) => {
alert('Oops - upload failed : error = ' error);
});
}
function downloadFile() {
var file = getDownloadURL(ref(storage, 'some-child'))
.then((url) => {
// `url` is the download URL for 'some-child' and can be downloaded directly:
const xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.onload = (event) => {
const blob = xhr.response;
const a = document.getElementById('downloadanchor');
a.href = window.URL.createObjectURL(new Blob([blob], { type: "text/plain" }));
a.download = "demo.txt";
a.click();
alert('Successful download');
};
xhr.open('GET', url);
xhr.send();
})
.catch((error) => {
alert('Oops - download failed : error = ' error);
});
}
這當然有一個 html 前端。其原理如下:
<input id="fileitem" type="file"><br></br>
<button id="downloadbutton">Download</button>
<a id="downloadanchor" href="" download></a>
uj5u.com熱心網友回復:
聽起來您曾將用戶簽入一次,但從未將其簽出。Firebase 會保留用戶憑據并在頁面重新加載時恢復它們,然后將其與對資料庫的呼叫一起發送。這通常正是您想要的,但在這里它似乎妨礙了您。
如果你不想使用驗證可以用戶退出通過一次性呼叫signOut`:
import { getAuth, ... } from "firebase/auth";
const auth = getAuth();
signOut(auth).then(() => {
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/363625.html
標籤:javascript 火力基地 火力存储
下一篇:使用Kivy同時顯示多個時鐘
