在 Firebase Cloud Storage 安全性規則中使用條件

本指南以瞭解 Firebase Security Rules 語言的核心語法指南為基礎,說明如何為 Cloud Storage 的 Firebase Security Rules 新增條件。

Cloud Storage Security Rules 的主要建構區塊是「條件」。條件是布林運算式,可決定是否應允許或拒絕特定作業。如果是基本規則,使用 true 和 false 常值做為條件的效果非常好。不過,Cloud Storage 語言的 Firebase Security Rules 可讓您編寫更複雜的條件,例如:

  • 檢查使用者驗證
  • 驗證傳入資料

如需 AI 輔助,請將下方提示詞複製到 AI 程式設計代理 (例如 Android Studio 內建 Gemini、Antigravity、Claude Code、Codex 和 Cursor)。您可以自訂提示,並與代理反覆調整。如需詳細安裝資訊,請參閱 Firebase 代理技能。

Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me write, validate, and deploy Firebase Security Rules to protect my app's Cloud Storage data.

驗證

Cloud Storage 專用的 Firebase Security Rules 與 Firebase Authentication 整合,為 Cloud Storage 提供強大的使用者驗證功能。這樣就能根據 Firebase Authentication 權杖的宣告,精細控管存取權。

當通過驗證的使用者對 Cloud Storage 執行要求時,系統會將使用者的 uid (request.auth.uid) 以及 Firebase Authentication JWT (request.auth.token) 的憑證附加資訊填入 request.auth 變數。

此外,使用自訂驗證時,request.auth.token 欄位會顯示額外的宣告。

當未經驗證的使用者執行要求時,request.auth 變數為 null。

您可以使用這項資料,透過幾種常見方式使用驗證機制保護檔案:

  • 公開:忽略 request.auth
  • 已驗證私人:檢查 request.auth 是否不為 null
  • 使用者私人:檢查 request.auth.uid 是否等於路徑 uid
  • 群組私人:檢查自訂權杖的憑證資訊是否與所選憑證資訊相符,或讀取檔案中繼資料,查看是否存在中繼資料欄位

公開

任何不考慮 request.auth 資訊的規則,都可視為 public 規則,因為這類規則不會考量使用者的驗證資訊。這些規則可用於顯示公開資料,例如遊戲資產、音效檔案或其他靜態內容。

// Anyone to read a public image if the file is less than 100kB
// Anyone can upload a public file ending in '.txt'
match /public/{imageId} {
  allow read: if resource.size < 100 * 1024;
  allow write: if imageId.matches(".*\\.txt");
}

已驗證的私人

在某些情況下,您可能希望應用程式的所有已驗證使用者都能查看資料,但未經驗證的使用者則無法查看。由於所有未經驗證的使用者,其 request.auth 變數都是 null,因此您只需檢查 request.auth 變數是否存在,即可要求驗證:

// Require authentication on all internal image reads
match /internal/{imageId} {
  allow read: if request.auth != null;
}

使用者 (私人)

到目前為止,request.auth 最常見的用途是為個別使用者提供檔案的精細權限:從上傳個人資料相片到讀取私人文件。

由於 Cloud Storage 中的檔案具有完整的檔案「路徑」,因此只要在檔案名稱前置字串中加入不重複的使用者識別資訊 (例如使用者的 uid),即可讓使用者控制檔案,並在評估規則時檢查該資訊:

// Only a user can upload their profile picture, but anyone can view it
match /users/{userId}/profilePicture.png {
  allow read;
  allow write: if request.auth.uid == userId;
}

群組私人

另一個同樣常見的用途是允許物件的群組權限,例如允許多位團隊成員在共用文件上協作。有幾種方法可以做到這一點:

  • 鑄造包含群組成員額外資訊 (例如群組 ID) 的Firebase Authentication自訂權杖
  • 在檔案中繼資料中加入群組資訊 (例如群組 ID 或授權uid清單)

這項資料儲存在權杖或檔案中繼資料後,即可在規則中參照:

// Allow reads if the group ID in your token matches the file metadata's `owner` property
// Allow writes if the group ID is in the user's custom token
match /files/{groupId}/{fileName} {
  allow read: if resource.metadata.owner == request.auth.token.groupId;
  allow write: if request.auth.token.groupId == groupId;
}

申請評估

系統會使用傳送至 Cloud Storage 的 request,評估上傳、下載、中繼資料變更和刪除作業。除了上述 request.auth 物件中的使用者專屬 ID 和 Firebase Authentication 酬載外,request 變數還包含執行要求的檔案路徑、收到要求的時間,以及要求為寫入時的新 resource 值。

request 物件也包含使用者的專屬 ID 和 request.auth 物件中的 Firebase Authentication 酬載,詳情請參閱使用者安全性一節。

request 物件的完整屬性清單如下:

屬性 類型 說明
auth <string, string> 對應 使用者登入時,提供 uid (使用者的專屬 ID) 和 token (Firebase Authentication JWT 憑證附加資訊的對應)。否則,系統會將其視為 null。
params <string, string> 對應 包含要求查詢參數的地圖。
path 路徑 代表要求執行路徑的 path。
resource <string, string> 對應 新的資源值,僅出現在 write 要求中。
time 時間戳記 時間戳記,代表評估要求時的伺服器時間。

資源評估

評估規則時,您可能也想評估上傳、下載、修改或刪除的檔案中繼資料。這樣一來,您就能建立複雜而強大的規則,例如只允許上傳特定內容類型的檔案,或只允許刪除超過特定大小的檔案。

Cloud Storage 的 Firebase Security Rules 會在 resource 物件中提供檔案中繼資料,其中包含 Cloud Storage 物件中顯示的中繼資料鍵/值組合。您可以在 read 或 write 要求中檢查這些屬性,確保資料完整性。

在 write 要求 (例如上傳、中繼資料更新和刪除) 中,除了 resource 物件 (包含要求路徑中目前存在的檔案中繼資料) 之外,您還可以使用 request.resource 物件,其中包含在允許寫入時要寫入的檔案中繼資料子集。您可以使用這兩個值,確保資料完整性或強制執行應用程式限制,例如檔案類型或大小。

resource 物件的完整屬性清單如下:

屬性 類型 說明
name 字串 物件的全名
bucket 字串 這個物件所在值區的名稱。
generation int 這個物件的Google Cloud Storage 物件世代。
metageneration int 這個物件的Google Cloud Storage 物件中繼層代。
size int 物件大小 (以位元組為單位)。
timeCreated 時間戳記 代表物件建立時間的時間戳記。
updated 時間戳記 代表物件上次更新時間的時間戳記。
md5Hash 字串 物件的 MD5 雜湊。
crc32c 字串 物件的 crc32c 雜湊。
etag 字串 與這個物件相關聯的 etag。
contentDisposition 字串 與這個物件相關聯的內容配置。
contentEncoding 字串 與這個物件相關聯的內容編碼。
contentLanguage 字串 與這個物件相關聯的內容語言。
contentType 字串 與這個物件相關聯的內容類型。
metadata <string, string> 對應 開發人員指定的其他自訂中繼資料鍵/值組合。

request.resource 包含上述所有項目,但 generation、metageneration、etag、timeCreated 和 updated 除外。

使用 Cloud Firestore 美化

您可以存取 Cloud Firestore 中的文件,評估其他授權條件。

使用 firestore.get() 和 firestore.exists() 函式,安全性規則可以根據 Cloud Firestore 中的文件評估傳入的要求。firestore.get() 和 firestore.exists() 函式都需要完整指定的文件路徑。使用變數建構 firestore.get() 和 firestore.exists() 的路徑時,您必須使用 $(variable) 語法明確逸出變數。

在下例中,我們可以看到一項規則,限制只有特定社團成員的使用者才能讀取檔案。

service firebase.storage {
  match /b/{bucket}/o {
    match /users/{club}/files/{fileId} {
      allow read: if club in
        firestore.get(/databases/(default)/documents/users/$(request.auth.id)).data.memberships
    }
  }
}
在下一個範例中,只有使用者的好友可以查看他們的相片。
service firebase.storage {
  match /b/{bucket}/o {
    match /users/{userId}/photos/{fileId} {
      allow read: if
        firestore.exists(/databases/(default)/documents/users/$(userId)/friends/$(request.auth.id))
    }
  }
}

建立並儲存第一個使用這些 Cloud Firestore 函式的 Cloud Storage Security Rules 後,Firebase 控制台或 Firebase CLI 會提示您啟用權限,連結這兩項產品。

如要停用這項功能,請按照「管理及部署 Firebase Security Rules」一文所述,移除 IAM 角色。

驗證資料

Firebase Security Rules for Cloud Storage 也可以用於資料驗證,包括驗證檔案名稱和路徑,以及檔案中繼資料屬性,例如 contentType 和 size。

service firebase.storage {
  match /b/{bucket}/o {
    match /images/{imageId} {
      // Only allow uploads of any image file that's less than 5MB
      allow write: if request.resource.size < 5 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
    }
  }
}

自訂函式

隨著Firebase Security Rules變得越來越複雜,您可能需要將一組條件包裝在函式中,以便在規則集中重複使用。安全性規則支援自訂函式。自訂函式的語法與 JavaScript 類似,但 Firebase Security Rules 函式是以特定領域語言編寫,有一些重要限制:

  • 函式只能包含一個 return 陳述式。不得包含任何其他邏輯。例如,無法執行迴圈或呼叫外部服務。
  • 函式可以自動存取定義範圍內的函式和變數。舉例來說,在 service firebase.storage 範圍內定義的函式可以存取 resource 變數,而 Cloud Firestore 則只能存取 get() 和 exists() 等內建函式。
  • 函式可以呼叫其他函式,但不得遞迴。呼叫堆疊深度總計上限為 10。
  • 在 rules2 版本中,函式可以使用 let 關鍵字定義變數。函式可以有任意數量的 let 繫結,但必須以 return 敘述結尾。

函式是以 function 關鍵字定義,並接受零或多個引數。舉例來說,您可能想將上述範例中使用的兩種條件合併為單一函式:

service firebase.storage {
  match /b/{bucket}/o {
    // True if the user is signed in or the requested data is 'public'
    function signedInOrPublic() {
      return request.auth.uid != null || resource.data.visibility == 'public';
    }
    match /images/{imageId} {
      allow read, write: if signedInOrPublic();
    }
    match /mp3s/{mp3Ids} {
      allow read: if signedInOrPublic();
    }
  }
}

在 Firebase Security Rules 中使用函式,可讓規則在變得更複雜時更容易維護。

後續步驟

討論完條件後,您對規則有了更深入的瞭解,可以開始:

瞭解如何處理核心用途,以及開發、測試和部署規則的工作流程: