基本安全性規則

Firebase Security Rules可讓您控管儲存資料的存取權。靈活的規則語法可讓您建立符合任何條件的規則,從對整個資料庫的所有寫入作業,到對特定文件的作業,都能涵蓋在內。

本指南說明一些較基本的用途,您在設定應用程式和保護資料時,可能會想實作這些用途。不過,在開始編寫規則之前,建議您進一步瞭解規則的編寫語言和行為。

如要存取及更新規則,請按照「管理及部署 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 data.

預設規則:鎖定模式

在 Firebase 控制台中建立資料庫或儲存空間執行個體時,您可以選擇 Firebase Security Rules 是否要限制資料存取權 (鎖定模式),或允許任何人存取 (測試模式)。在 Cloud Firestore 和 Realtime Database 中,鎖定模式的預設規則會拒絕所有使用者的存取。在 Cloud Storage 中,只有通過驗證的使用者可以存取儲存空間值區。

Cloud Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

Realtime Database

{
  "rules": {
    ".read": false,
    ".write": false
  }
}

Cloud Storage

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
  }
}

開發環境規則

在開發應用程式時,您可能需要相對開放或不受限制的資料存取權。請務必先更新 Security Rules,再將應用程式部署至正式環境。另外請注意,部署應用程式後,即使尚未推出,應用程式仍會公開。

請注意,Firebase 允許用戶端直接存取資料,而Firebase Security Rules是唯一能防止惡意使用者存取的安全防護機制。將規則與產品邏輯分開定義有許多優點:用戶端不負責強制執行安全性、有錯誤的實作不會危害資料,最重要的是,您不必依賴中介伺服器來保護資料,避免資料外洩。

所有已驗證的使用者

雖然我們不建議讓任何已登入的使用者存取您的資料,但在開發應用程式時,將存取權設為任何已驗證的使用者可能會很有幫助。

Cloud Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    match /some_collection/{document} {
      allow read, write: if request.auth != null;
    }
  }
}

Realtime Database

{
  "rules": {
    "some_path": {
      ".read": "auth.uid !== null",
      ".write": "auth.uid !== null"
    }
  }
}

Cloud Storage

service firebase.storage {
  match /b/{bucket}/o {
    match /some_folder/{fileName} {
      allow read, write: if request.auth != null;
    }
  }
}

可用於正式環境的規則

準備部署應用程式時,請務必保護資料,並正確授予使用者存取權。使用 Authentication 設定使用者存取權,並直接從資料庫讀取資料,設定資料存取權。

建議您在建構資料時編寫規則,因為規則的設定方式會影響您如何限制不同路徑的資料存取權。

僅限內容擁有者存取

這些規則會限制只有經過驗證的內容擁有者才能存取。資料只能由一位使用者讀取和寫入,且資料路徑包含使用者的 ID。

這項規則的適用時機:如果資料是依使用者區隔,也就是只有建立資料的使用者需要存取資料,這項規則就很適用。

這項規則不適用的情況:如果有多位使用者需要寫入或讀取相同資料,這組規則就不適用,因為使用者會覆寫資料,或無法存取自己建立的資料。

如何設定這項規則:建立規則,確認要求讀取或寫入資料的使用者是該資料的擁有者。

Cloud Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /some_collection/{userId}/{document} {
      allow read, write: if request.auth != null && request.auth.uid == userId
    }
  }
}

Realtime Database

{
  "rules": {
    "some_path": {
      "$uid": {
        // Allow only authenticated content owners access to their data
        ".read": "auth !== null && auth.uid === $uid",
        ".write": "auth !== null && auth.uid === $uid"
      }
    }
  }
}

Cloud Storage

// Grants a user access to a node matching their user ID
service firebase.storage {
  match /b/{bucket}/o {
    // Files look like: "user/<UID>/file.txt"
    match /user/{userId}/{fileName} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

混合公開和私人存取權

這項規則允許任何人讀取資料集,但只有經過驗證的內容擁有者,才能在指定路徑建立或修改資料。

這項規則的適用時機:如果應用程式需要公開可讀取的元素,但必須限制只有這些元素的擁有者才能編輯,這項規則就很適用。例如即時通訊應用程式或網誌。

這項規則不適用的情況:與僅限內容擁有者規則一樣,如果有多位使用者需要編輯相同資料,這項規則集就不適用。使用者最終會覆寫彼此的資料。

設定這項規則:建立規則,讓所有使用者 (或所有通過驗證的使用者) 都能讀取資料,並確認寫入資料的使用者是擁有者。

Cloud Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow public read access, but only content owners can write
    match /some_collection/{document} {
      // Allow public reads
      allow read: if true
      // Allow creation if the current user owns the new document
      allow create: if request.auth.uid == request.resource.data.author_uid;
      // Allow updates by the owner, and prevent change of ownership
      allow update: if request.auth.uid == request.resource.data.author_uid
                    && request.auth.uid == resource.data.author_uid;
      // Allow deletion if the current user owns the existing document
      allow delete: if request.auth.uid == resource.data.author_uid;
    }
  }
}

Realtime Database

{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data

  "rules": {
    "some_path": {
      "$uid": {
        ".read": true,
        // or ".read": "auth.uid !== null" for only authenticated users
        ".write": "auth.uid === $uid"
      }
    }
  }
}

Cloud Storage

service firebase.storage {
  match /b/{bucket}/o {
    // Files look like: "user/<UID>/file.txt"
    match /user/{userId}/{fileName} {
      allow read;
      allow write: if request.auth.uid == userId;
    }
  }
}

屬性式和角色式存取權

如要讓這些規則生效,您必須在資料中定義並指派屬性給使用者。Firebase Security Rules 根據資料庫或檔案中繼資料的資料檢查要求,確認或拒絕存取。

規則運作時機:指派角色給使用者時,這項規則可讓您根據角色或特定使用者群組限制存取權。舉例來說,如果您要儲存成績,可以為「學生」群組 (只能讀取內容)、「老師」群組 (可讀取及寫入其科目) 和「校長」群組 (可讀取所有內容) 指派不同的存取層級。

這項規則不適用的情況:在 Realtime Database 和 Cloud Storage 中,規則無法使用 Cloud Firestore 規則可納入的 get() 方法。因此,您必須建構資料庫或檔案中繼資料,以反映規則中使用的屬性。

如要設定這項規則:請在 Cloud Firestore 中,於使用者文件中加入可讀取的欄位,然後設定規則來讀取該欄位,並依條件授予存取權。在 Realtime Database 中,建立資料路徑來定義應用程式的使用者,並授予他們子節點中的角色。

您也可以在 Authentication 中設定自訂宣告,然後在任何 Firebase Security Rules 中從 auth.token 變數擷取該資訊。

資料定義的屬性和角色

這些規則僅適用於Cloud Firestore和Realtime Database。

Cloud Firestore

請注意,只要規則包含讀取作業 (如下列規則),系統就會向您收取 Cloud Firestore 讀取作業費用。

service cloud.firestore {
  match /databases/{database}/documents {
    // For attribute-based access control, Check a boolean `admin` attribute
    allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
    allow read: true;

    // Alterntatively, for role-based access, assign specific roles to users
    match /some_collection/{document} {
     allow read: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Reader"
     allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Writer"
   }
  }
}

Realtime Database

{
  "rules": {
    "some_path": {
      "${subpath}": {
        //
        ".write": "root.child('users').child(auth.uid).child('role').val() === 'admin'",
        ".read": true
      }
    }
  }
}

自訂宣告屬性和角色

如要實作這些規則,請在 Firebase Authentication 中設定自訂宣告,然後在規則中使用這些宣告。

Cloud Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    // For attribute-based access control, check for an administrator claim
    allow write: if request.auth.token.admin == true;
    allow read: true;

    // Alterntatively, for role-based access, assign specific roles to users
    match /some_collection/{document} {
     allow read: if request.auth.token.reader == "true";
     allow write: if request.auth.token.writer == "true";
   }
  }
}

Realtime Database

{
  "rules": {
    "some_path": {
      "$uid": {
        // Create a custom claim for each role or group
        // you want to use
        ".write": "auth.uid !== null && auth.token.writer === true",
        ".read": "auth.uid !== null && auth.token.reader === true"
      }
    }
  }
}

Cloud Storage

service firebase.storage {
  // 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;
  }
}

租約屬性

如要實作這些規則,請在 Google Cloud Identity Platform (GCIP) 中設定多用戶群架構,然後在規則中使用用戶群。以下範例允許特定租戶中的使用者寫入,例如 tenant2-m6tyz

Cloud Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    // For tenant-based access control, check for a tenantID
    allow write: if request.auth.token.firebase.tenant == 'tenant2-m6tyz';
    allow read: true;
  }
}

Realtime Database

{
  "rules": {
    "some_path": {
      "$uid": {
        // Only allow reads and writes if user belongs to a specific tenant
        ".write": "auth.uid !== null && auth.token.firebase.tenant === 'tenant2-m6tyz'",
        ".read": "auth.uid !== null
      }
    }
  }
}

Cloud Storage

service firebase.storage {
  // Only allow reads and writes if user belongs to a specific tenant
  match /files/{tenantId}/{fileName} {
    allow read: if request.auth != null;
    allow write: if request.auth.token.firebase.tenant == tenantId;
  }
}