Identifying your user is only part of security. Once you know who they are, you need a way to control their access to data in your database. Firebase Database Rules allow you to control access for each user. For example, here's a set of security rules that allows anyone to read the path /foo/
, but no one to write to it:
{
"rules": {
"foo": {
".read": true,
".write": false
}
}
}
.read
and .write
rules cascade, so this ruleset grants read access to any data at path /foo/ as well as any deeper paths such as /foo/bar/baz
. Note that .read
and .write
rules that permit access will override other rules in the database that do not allow access; in other words all applicable, .read
and .write
rules are ORed together). So read access to /foo/bar/baz
would still be granted in this example even if a rule at the path /foo/bar/baz
evaluated to false.
The Firebase Database Rules include built-in variables and functions that allow you to refer to other paths, server-side timestamps, authentication information, and more. Here's an example of a rule that grants write access for authenticated users to /users/<uid>/
, where is the ID of the user obtained through Firebase Authentication.
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}