kjones1876
kjones1876

Reputation: 762

Set a security rule firebase based on a users oauth email

Is there a way to securely get the email that they OAuthed in with in a security rule.

Ideally i wanted to create a rule like:

{
    ".read": "auth.google.email.matches(/@example.com$/)"
    ".write": "auth.google.email.matches(/@example.com$/)"
}

So that the entire application, or section of an application is secured to an email address suffix. This is a much easier of way to manage my application because the users will be given access based on the company email they have, all or nothing.

Alternatively is theres a way to save the users email address to the database which they then cant write to i believe i could achieve a similar process.

Upvotes: 5

Views: 687

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

The auth. properties of OAuth providers are not available in security rules. Per the documentation on the auth variable:

The predefined auth variable is null before authentication takes place. Once a user is authenticated by Firebase Login's auth method, it will contain the following attributes:

provider The authentication method used ("password", "anonymous", "facebook", "github", "google", or "twitter").

uid A unique user id, guaranteed to be unique across all providers.

So you cannot secure the data based on the email address, unless you involve a server to provide the email domain in a secure way.

Once you involve a server, you can either:

  • verify the email address and store the verified email address in the database. Then you can access it in your security rules with something like root.child('users').child(auth.uid).child('emailDomain').val()
  • mint your own tokens that include the email domain, so that it becomes available in the the auth variable in your security rules with something like auth.emailDomain.

Upvotes: 3

Related Questions