Firebase Authentication Admin Login Only

Viewed 408

I'm building two Flutter apps that will use the same Firebase project.

The first app is public and used by users to create accounts, login and use the application within the allowed access rules.

The second is for admins to approve user posts.

You have to login to use both apps. With the first anyone can create an account and login. Admins can also login with the same admin account. But with the second only admin users should be able to login. I'm enforcing security via access rules. But I need the second admin app to reject non-admin users from login in in the first place. So I can't simply create a collection and put the admin user UIDs in it.

How do I differentiate regular users from admin users, and most importantly use that differentiation to disallow non-admin users from login in into the admin app?

Currently for login I'm simply using

FirebaseAuth.instance
        .signInWithEmailAndPassword(email: email, password: password);

I read about something called user claims, but there doesn't seem to be a way to modify this in the dashboard nor is there a way to specify some kind of condition via the code above.

I hope this makes enough sense.

Thank you all

1 Answers

You cannot prevent anyone from logging in to your application. The best you can do is check if the user is an admin. If yes, proceed else force logout them. You can use Firebase Custom Claims to add admin users or you can even store their UIDs in Firestore or Realtime Database.

UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
  email: "barry.allen@example.com",
  password: "SuperSecretPassword!"
);

// Check for claims here
if (admin) { 
  //...
} else {
  await FirebaseAuth.instance.signOut();
  // or just show alert that user is not an admin
}

You can use the getIdTokenResult method to get user's custom claims. This answer explains how to verify custom claims in Flutter.

Related