Firestoreのセキュリティ ルールについて
Firestoreの読み書きに対してセキュリティルールを設定できる。
これを設定せずに公式のすべて許可の例
https://firebase.google.com/docs/firestore/security/get-started?hl=ja#allow-all
のようにして運用すると読み書きし放題になってしまう。
実際の書き方
コードは公式から 「ユーザーが自分のデータのみを読み書きできるようにする」の例
Cloud Firestore セキュリティ ルールの条件の記述 | Firebase
service cloud.firestore { match /databases/{database}/documents { // Make sure the uid of the requesting user matches name of the user // document. The wildcard expression {userId} makes the userId variable // available in rules. match /users/{userId} { allow read, update, delete: if request.auth.uid == userId; allow create: if request.auth.uid != null; } } }
auth 変数はリクエスト送信者の認証情報であり、この認証情報はセキュリティルールによく使う
https://firebase.google.com/docs/reference/rules/rules.firestore.Request?hl=ja#auth
認証情報はカスタム クレームを設定して開発者が独自に定義することが出来る
例:管理者と一般ユーザー等
上記のソースコードでは、 deleteはリクエストがユーザー本人でなければならないことや、createは認証情報のuidが入っているユーザーでなければならないことが記載されています。