3

Can I validate email domain zone in Firebase Authentication?

For example, I want to give success registration just for an email from yahoo and gmail (@yahoo.com, @gmail.com emails)

p.s. of course I can validate it in client side, but this isn't enough

Hristo Eftimov
  • 13,845
  • 13
  • 50
  • 77
Art Olshansky
  • 3,032
  • 1
  • 19
  • 25

1 Answers1

4

Unfortunately, you can not validate the email's domain before registration (exclude the client side).

There are some options in front of you, that you can do:

  • Option 1: To prevent access to the database and storage if the user's domain is not some of your specific domains:

For example:

"rules": {
    ".read": "auth.token.email.endsWith('@gmail.com')",
    ".write": "auth.token.email.endsWith('@gmail.com')"
  }
}

or like this:

"rules": {
    ".read": "auth.token.email_verified == true && auth.token.email.matches(/.*@gmail.com$/)",
    ".write": "auth.token.email_verified == true && auth.token.email.matches(/.*@gmail.com$/)"
  }
}

Credits: https://stackoverflow.com/a/38019847/2765346

  • Option 2: To add a Firebase Authentication trigger and listen for new users. Then you can validate the new registered users and disable these with invalid domains:

For example:

exports.validateUser = functions.auth.user().onCreate((user) => {
   if (!user.email.matches(/.*@gmail.com$/)) {
       admin.auth().updateUser(data, {
           disabled: true
       });
   }
});

Credits: https://firebase.google.com/docs/functions/auth-events

Hristo Eftimov
  • 13,845
  • 13
  • 50
  • 77
  • When I use `request.auth.token.email.endsWith('@mydomain.com');` it gives error `Missing or insufficient permissions` it only works for me when I use `request.auth.token.email == 'user1@mydomain.com'` – A.W. Dec 27 '19 at 09:17