Saturday, October 8, 2022

Security Rules and Firebase Authentication

Firebase Security Rules provide access control and data validation in a format that supports multiple levels of complexity. To build user-based and role-based access systems that keep your users' data safe, use Firebase Authentication with Firebase Security Rules.

Authentication identifies users requesting access to your data and provides that information as a variable you can leverage in your rules. The auth variable contains the following information:

uid: A unique user ID, assigned to the requesting user.

token: A map of values collected by Authentication.

The auth.token variable contains the following values:

email The email address associated with the account, if present.

email_verified true if the user has verified they have access to the email address. Some providers automatically verify email addresses they own.

phone_number The phone number associated with the account, if present.

name The user's display name, if set.

sub The user's Firebase UID. This is unique within a project.

firebase.identities Dictionary of all the identities that are associated with this user's account. The keys of the dictionary can be any of the following: email, phone, google.com, facebook.com, github.com, twitter.com. The values of the dictionary are arrays of unique identifiers for each identity provider associated with the account. For example, auth.token.firebase.identities["google.com"][0] contains the first Google user ID associated with the account.

firebase.sign_in_provider The sign-in provider used to obtain this token. Can be one of the following strings: custom, password, phone, anonymous, google.com, facebook.com, github.com, twitter.com.

firebase.tenant The tenantId associated with the account, if present. e.g. tenant2-m6tyz

You can access custom claims in Rules after creating custom claims in Authentication. You can then reference those custom claims using the auth.token variable.


{

  "rules": {

    "some_path/$sub_path": {

      // Create a custom claim for the admin role

      ".write": "auth.uid !== null && auth.token.writer === true"

      ".read": "auth.uid !== null"

      }

    }

  }


references:

https://firebase.google.com/docs/rules/rules-and-auth

No comments:

Post a Comment