Chapter 20

データベースのセキュリティルール

snova301
snova301
2022.07.18に更新

Firebaseのセキュリティルールとは

Firebaseのセキュリティルールとは、保管されたデータへのアクセスをどう許可するかを定義するための構文です。

https://firebase.google.com/docs/rules?hl=ja

Firestore、Realtime Database、Cloud Storageのそれぞれで構文が異なります。

https://firebase.google.com/docs/rules/rules-language

Firestoreの構文

Firestoreのセキュリティルールの構文はCommon Expression Language(CEL)をベースとした言語が採用されています。

基本的なセキュリティルールとして、認証済のすべてのユーザーがアクセス可能なテスト環境では、以下のように記述します。

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

また、コンテンツ所有者のみがアクセスできる本番環境では、以下のように記述します。

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

https://firebase.google.com/docs/firestore/security/rules-structure?authuser=0

Realtime Database

Realtime Databaseのセキュリティルールの構文はjson形式が採用されています。

コンテンツ所有者のみがアクセスできるようにするためには、以下の通り設定します。

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

https://firebase.google.com/docs/database/security?authuser=0

Cloud Storage

Cloud Storageのセキュリティルールの構文はCommon Expression Language(CEL)をベースとした言語が採用されています。

コンテンツ所有者のみがアクセスできるセキュリティルールは以下のとおりです。

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

https://firebase.google.com/docs/storage/security?authuser=0