基本安全規則

Firebase 安全性規則可讓您控制對儲存資料的存取。靈活的規則語法意味著您可以建立符合任何內容的規則,從整個資料庫的所有寫入到對特定文件的操作。

本指南介紹了您在設定應用程式和保護資料時可能想要實現的一些更基本的用例。但是,在開始編寫規則之前,您可能想要了解有關編寫規則所使用的語言及其行為的更多資訊。

若要存取和更新您的規則,請依照管理和部署 Firebase 安全性規則中概述的步驟操作。

預設規則:鎖定模式

當您在 Firebase 控制台中建立資料庫或儲存實例時,您可以選擇 Firebase 安全性規則是限制對您的資料的存取(鎖定模式)還是允許任何人存取(測試模式)。在 Cloud Firestore 和 Realtime Database 中,鎖定模式的預設規則拒絕所有使用者的存取。在 Cloud Storage 中,只有經過驗證的使用者才能存取儲存桶。

雲端Firestore

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

即時資料庫

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

雲端儲存

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

開發環境規則

當您開發應用程式時,您可能希望相對開放或不受限制地存取您的資料。請務必在將應用程式部署到生產環境之前更新您的規則。另請記住,如果您部署了應用程序,它就可以公開訪問 - 即使您尚未啟動它。

請記住,Firebase 允許客戶端直接存取您的數據,而 Firebase 安全性規則是阻止惡意使用者存取的唯一保障措施。與產品邏輯分開定義規則有很多優點:客戶端不負責強制執行安全性,有缺陷的實現不會損害您的數據,最重要的是,您不依賴中間伺服器來保護數據免受外界侵害。

所有經過身份驗證的用戶

雖然我們不建議讓任何已登入的使用者都可以存取您的數據,但在開發應用程式時設定對任何經過身份驗證的使用者的存取權限可能會很有用。

雲端Firestore

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

即時資料庫

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

雲端儲存

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

生產就緒規則

當您準備部署應用程式時,請確保您的資料受到保護,並且存取權限已正確授予您的使用者。利用身份驗證來設定基於用戶的訪問,並直接從資料庫讀取以設定基於資料的存取。

考慮在建立資料時編寫規則,因為設定規則的方式會影響如何限制對不同路徑上的資料的存取。

僅限內容所有者訪問

這些規則僅限制經過身份驗證的內容所有者的存取。資料只能由一個使用者讀寫,且資料路徑包含使用者的ID。

當此規則起作用時:如果資料由使用者隔離,則此規則效果很好 - 如果需要存取資料的唯一使用者是建立資料的相同使用者。

當此規則不起作用時:當多個使用者需要寫入或讀取相同資料時,此規則集不起作用 - 用戶將覆蓋資料或無法存取他們創建的資料。

若要設定此規則:建立一條規則,確認要求讀取或寫入資料的存取權限的使用者是擁有該資料的使用者。

雲端Firestore

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

即時資料庫

{
  "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"
      }
    }
  }
}

雲端儲存

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

公共和私人混合訪問

此規則允許任何人讀取資料集,但僅限經過身份驗證的內容所有者在給定路徑上建立或修改資料的能力。

當此規則有效時:此規則適用於需要公開可讀元素但需要限制對這些元素擁有者的編輯存取權的應用程式。例如,聊天應用程式或部落格。

當此規則不起作用時:與僅限內容所有者規則一樣,當多個使用者需要編輯相同資料時,此規則集不起作用。用戶最終將覆蓋彼此的數據。

若要設定此規則:建立一條規則,啟用所有使用者(或所有經過驗證的使用者)的讀取存取權限,並確認寫入資料的使用者是擁有者。

雲端Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow public read access, but only content owners can write
    match /some_collection/{document} {
      allow read: if true
      allow create: if request.auth.uid == request.resource.data.author_uid;
      allow update, delete: if request.auth.uid == resource.data.author_uid;
    }
  }
}

即時資料庫

{
// 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"
      }
    }
  }
}

雲端儲存

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

基於屬性和基於角色的訪問

為了使這些規則發揮作用,您必須定義屬性並將其指派給資料中的使用者。 Firebase 安全性規則會根據資料庫或檔案元資料中的資料檢查請求,以確認或拒絕存取。

當此規則起作用時:如果您要向使用者指派角色,則此規則可以輕鬆地根據角色或特定使用者群組限制存取。例如,如果您要儲存成績,則可以為「學生」群組(僅讀取其內容)、「教師」群組(讀取和寫入其主題)和「校長」群組(讀取其內容)分配不同的訪問級別。所有內容)。

當此規則不起作用時:在即時資料庫和 Cloud Storage 中,您的規則無法利用 Cloud Firestore 規則可以合併的get()方法。因此,您必須建立資料庫或文件元資料以反映您在規則中使用的屬性。

要設定此規則,請執行以下操作:在 Cloud Firestore 中,在使用者的文件中包含一個您可以讀取的字段,然後建立您的規則以讀取該字段並有條件地授予存取權限。在即時資料庫中,建立一個資料路徑來定義應用程式的使用者並授予他們在子節點中的角色。

您也可以在驗證中設定自訂聲明,然後從任何 Firebase 安全性規則中的auth.token變數擷取該資訊。

資料定義的屬性和角色

這些規則僅適用於 Cloud Firestore 和即時資料庫。

雲端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"
   }
  }
}

即時資料庫

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

自訂聲明屬性和角色

若要實作這些規則,請在 Firebase 驗證中設定自訂聲明,然後利用規則中的聲明。

雲端Firestore

service cloud.firestore {
  match /databases/{database}/documents {
    // For attribute-based access control, check for an admin 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";
   }
  }
}

即時資料庫

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

雲端儲存

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

雲端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;
  }
}

即時資料庫

{
  "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
      }
    }
  }
}

雲端儲存

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;
  }
}