Use this guide to understand common vulnerabilities in Cloud Firestore Security Rules configurations, review and better secure your own rules, and test your changes before deploying them.
If you receive an alert that your Cloud Firestore database isn't properly secured, you can resolve the vulnerabilities by modifying and testing your Cloud Firestore Security Rules .
To view your existing Security Rules, go to the Rules tab in the Firebase console.
Разберитесь Cloud Firestore Security Rules
Cloud Firestore Security Rules защищают ваши данные от злоумышленников. Правила по умолчанию для любого экземпляра Cloud Firestore , созданного в консоли Firebase , запрещают доступ всем пользователям. Для разработки приложения и доступа к базе данных вам потребуется изменить эти правила и, возможно, рассмотреть возможность предоставления общего доступа всем пользователям в среде разработки. Однако, прежде чем развертывать приложение в производственной среде, уделите время правильной настройке правил и защите ваших данных.
As you're developing your app and testing different configurations for your rules, use the Cloud Firestore emulator to run your app in a local development environment.
Типичные сценарии с небезопасными правилами
Перед развертыванием приложения необходимо проверить и обновить Cloud Firestore Security Rules которые вы могли установить по умолчанию или в процессе первоначальной разработки приложения с использованием Cloud Firestore . Убедитесь, что вы надлежащим образом защитили данные пользователей, избегая следующих распространенных ошибок.
Открытый доступ
При настройке Cloud Firestore вы, возможно, задали правила, разрешающие открытый доступ во время разработки. Вам может казаться, что ваше приложение используется только вами, но если вы его развернули, оно доступно в интернете. Если вы не аутентифицируете пользователей и не настраиваете правила безопасности, то любой, кто угадает идентификатор вашего проекта, сможет украсть, изменить или удалить данные.
| Not recommended: Read and write access to all users. |
// Allow read/write access to all users under any conditions // Warning: **NEVER** use this rule set in production; it allows // anyone to overwrite your entire database. service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; } } }
| Solution: Rules that restrict read and write access. Создавайте правила, которые соответствуют вашей иерархии данных. Одним из распространенных решений этой проблемы является безопасность на основе пользователей с помощью Firebase Authentication . Узнайте больше об аутентификации пользователей с помощью правил . |
Только для владельцев контента
service cloud.firestore { match /databases/{database}/documents { // Allow only authenticated content owners access match /some_collection/{document} { // Allow reads and deletion if the current user owns the existing document allow read, delete: if request.auth.uid == resource.data.author_uid; // 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; } } }
Смешанный общественный и частный доступ
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; } } }
Доступ предоставляется любому авторизованному пользователю.
Иногда Cloud Firestore Security Rules проверяют, авторизован ли пользователь, но не ограничивают доступ на основе этой аутентификации. Если одно из ваших правил содержит auth != null , подтвердите, что вы хотите, чтобы любой авторизованный пользователь имел доступ к данным.
| Not recommended: Any logged-in user has read and write access to your entire database. |
service cloud.firestore { match /databases/{database}/documents { match /some_collection/{document} { allow read, write: if request.auth != null; } } }
| Solution: Narrow access using security conditions. При проверке аутентификации вы также можете использовать одно из свойств аутентификации для дальнейшего ограничения доступа к определенным наборам данных для конкретных пользователей. Узнайте больше о добавлении условий безопасности и доступа на основе ролей . |
Доступ на основе ролей
service cloud.firestore { match /databases/{database}/documents { // Assign roles to all users and refine access based on user roles match /some_collection/{document} { allow read: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Reader" allow write: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "Writer" // Note: Checking for roles in your database using `get` (as in the code // above) or `exists` carry standard charges for read operations. } } }
Доступ на основе атрибутов
// Give each user in your database a particular attribute // and set it to true/false // Then, use that attribute to grant access to subsets of data // For example, an "admin" attribute set // to "true" grants write access to data service cloud.firestore { match /databases/{database}/documents { match /collection/{document} { allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true; allow read: true; } } }
Смешанный общественный и частный доступ
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 write: if request.auth.uid == request.resource.data.author_uid
}
}
}
Доступ к неподтвержденным адресам электронной почты
Иногда Cloud Firestore Security Rules проверяют, принадлежит ли электронная почта пользователя определенному домену. Хотя это, как правило, хорошая практика, электронные адреса не всегда подтверждаются при входе в систему, пока пользователь не выполнит дополнительный шаг после получения письма с подтверждением. Убедитесь, что вы проверяете, действительно ли электронная почта принадлежит пользователю.
| Not recommended: Any user can sign in with an arbitrary email address. |
service cloud.firestore { match /databases/{database}/documents { // Allow access based on email domain match /some_collection/{document} { allow read: if request.auth != null && request.auth.email.endsWith('@example.com') } } }
| Решение: Ограничить доступ только для подтвержденных адресов электронной почты. |
Подтвердите электронные письма
service cloud.firestore { match /databases/{database}/documents { // Allow access based on email domain match /some_collection/{document} { allow read: if request.auth != null && request.auth.email_verified && request.auth.email.endsWith('@example.com') } } }
Закрытый доступ
While you're developing your app, another common approach is to keep your data locked down. Typically, this means you've closed off read and write access to all users, as follows:
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
SDK администратора Firebase и Cloud Functions по-прежнему могут получать доступ к вашей базе данных. Используйте эти правила, если вы планируете использовать Cloud Firestore в качестве серверной части в сочетании с SDK администратора Firebase. Хотя это безопасно, следует проверить, могут ли клиенты вашего приложения корректно получать данные.
Learn more about Cloud Firestore Security Rules and how they work in Get Started with Cloud Firestore Security Rules .
Проверьте Cloud Firestore Security Rules
Чтобы проверить поведение вашего приложения и убедиться в корректности настроек Cloud Firestore Security Rules , используйте эмулятор Cloud Firestore . Эмулятор Cloud Firestore позволяет запускать и автоматизировать модульные тесты в локальной среде перед развертыванием каких-либо изменений.
To quickly test your updated Cloud Firestore Security Rules in the Firebase console, use the Rules Playground tool.

- To open the Rules Playground, click Rules playground from the Rules tab .
- In the Rules playground settings, select options for your test, including:
- Проверка операций чтения и записи.
- Укажите конкретное местоположение в вашей базе данных в виде пути.
- Authentication type — unauthenticated, authenticated anonymous user, or a specific user ID
- Document-specific data that your rules specifically reference (for example, if your rules require the presence of a specific field before allowing a write)
- Click Run and look for the results in the banner above the rules window.