Controle de acesso baseado no usuário
Implemente regras para conceder ou negar acesso de leitura e gravação com base nos IDs e nas funções dos usuários autenticados.
Controle de acesso baseado no usuário é uma aula grátis de Firebase Auth & Realtime Database Apps no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Firebase Auth & Realtime Database Apps, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Firebase Auth & Realtime Database Apps inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Control Access by User
Welcome to this lesson! In secure applications, it's crucial to control who can access what data. This is known as User-Based Access Control.
Firebase Realtime Database Security Rules allow you to define precise permissions based on the user who is currently logged in.
Meet the 'auth' Variable
Inside your security rules, Firebase provides a special auth variable. This variable contains information about the currently authenticated user.
auth.uid: The unique ID of the logged-in user.auth.token: An object containing custom claims and other token details (e.g., email).
If no user is logged in, auth will be null.
Authenticated Users Only
The simplest form of user-based access is to ensure only authenticated users can read or write any data.
You can achieve this by checking if the auth variable is not null.
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}Users Read Their Own Data
Often, you want users to only read data that belongs to them. Imagine a /users node where each user has a sub-node with their UID.
We can use a wildcard variable ($uid) in the path to match the current user's ID.
{
"rules": {
"users": {
"$uid": {
".read": "auth.uid == $uid"
}
}
}
}Users Write Their Own Data
Similarly, you can restrict write access so users can only modify their own data. This prevents one user from changing another's profile.
The rule is very similar to the read rule, just applied to .write.
{
"rules": {
"users": {
"$uid": {
".write": "auth.uid == $uid"
}
}
}
}Read & Write Your Own Profile
Let's combine the read and write rules. This common pattern allows users full control over their own specific data node, often used for user profiles.
Here, $userId is a placeholder for an actual user's UID.
{
"rules": {
"profiles": {
"$userId": {
".read": "auth.uid == $userId",
".write": "auth.uid == $userId"
}
}
}
}Post Ownership Example
Consider a 'posts' section where anyone can read posts, but only the creator can edit or delete their own post.
We assume each post object has an ownerId field. We use data.ownerId to refer to the existing owner ID in the database.
{
"rules": {
"posts": {
"$postId": {
".read": "true",
".write": "auth.uid == data.ownerId"
}
}
}
}Validating Data with Auth
Beyond just who can write, you can also validate what data they write. For instance, ensuring that when a user creates an item, they correctly set themselves as the owner.
The newData variable refers to the data being written.
{
"rules": {
"items": {
"$itemId": {
".write": "auth != null",
".validate": "newData.ownerId == auth.uid"
}
}
}
}Introducing User Roles
For more complex access, you can define roles like 'admin' or 'moderator'. These roles are often stored as custom claims in the user's authentication token.
You can then check for these roles in your rules using auth.token.
{
"rules": {
"adminContent": {
".read": "auth.token.isAdmin == true",
".write": "auth.token.isAdmin == true"
}
}
}Quick Check on Access
Consider the following Realtime Database Security Rules:
{
"rules": {
"messages": {
"$messageId": {
".read": "auth.uid == data.senderId",
".write": "auth.uid == data.senderId"
}
}
}
}If user "user123" is authenticated and tries to read a message where data.senderId is "user456", will they succeed?
Recap: User Access Rules
You've learned how to implement powerful user-based access control in Firebase Realtime Database Security Rules!
- The
authvariable provides current user details. - You can restrict access to authenticated users (
auth != null). - Users can be granted read/write access to their own specific data using
auth.uid == $uid. - You can validate incoming data using
newDataandauth.uid. - Roles can be used to grant access to specific user groups.
Next, explore how to validate the data itself!
Perguntas Frequentes
A aula “Controle de acesso baseado no usuário” é grátis?
Sim — o texto completo de “Controle de acesso baseado no usuário” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Firebase Auth & Realtime Database Apps, atualize para CoddyKit PRO. O curso de Firebase Auth & Realtime Database Apps inclui 4 aulas no total.
O que vou aprender em “Controle de acesso baseado no usuário”?
Implemente regras para conceder ou negar acesso de leitura e gravação com base nos IDs e nas funções dos usuários autenticados. Você pratica Firebase Auth & Realtime Database Apps com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Firebase Auth & Realtime Database Apps?
Nenhuma experiência prévia é necessária. Firebase Auth & Realtime Database Apps no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Controle de acesso baseado no usuário”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Firebase Auth & Realtime Database Apps?
Sim. Cada aula de Firebase Auth & Realtime Database Apps inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Compreendendo a sintaxe das regras de segurança
- Controle de acesso baseado no usuário
- Validando dados com regras
- Testes e Depuração de Regras de Segurança