Firebaseのセキュリティルールとは
Firebaseのセキュリティルールとは、保管されたデータへのアクセスをどう許可するかを定義するための構文です。
Firestore、Realtime Database、Cloud Storageのそれぞれで構文が異なります。
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
}
}
}
Realtime Database
Realtime Databaseのセキュリティルールの構文はjson
形式が採用されています。
コンテンツ所有者のみがアクセスできるようにするためには、以下の通り設定します。
{
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
}
}
}
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;
}
}
}