简体   繁体   中英

How to distinguish admin and customer role when create user with createUserWithEmailAndPassword firebase auth in ReactJS

I have two reactjs websites, one for client user and one for admin. I have graphql api for data access. Currently, admin is using JWT and we will change to firebase authentication.

I already implement both login and registration using firebase package.

here is the create user function. So it worked and can login successfully. But my question is that how can I distinguish admin user and customer user. I saw that setCustomUserClaims is only for firebase-admin. May I know how to set the role in firebase and what is the correct way to set?

function register(name, email, password) {
return createUserWithEmailAndPassword(auth, email, password).then((res) => {
  const auth = getAuth();
  
  updateProfile(auth.currentUser, {
    displayName: name
  }).then(() => {
    // Profile updated!
    // ...
  }).catch((error) => {
    // An error occurred
    // ...
    console.log(error.message);
  });
});

}

Custom claims are definitely the easiest way to add roles in Firebase Auth but you'll need to use Admin SDK in a Cloud function or any secure server environment.

I saw that setCustomUserClaims is only for firebase-admin

setCustomUserClaims() is used to set the custom claims but you can always read them using getIdTokenResult() function in client SDK.

const { claims } = await getIdTokenResult(auth.currentUser)

So if your GraphQL API runs on your own server you can install Firebase Admin there and add custom claims to Firebase auth users.

Alternatively, you can store user role in a database like Firestore or your own database and read user's role from there. One catch of store roles in a database is that you cannot access them from security rules of other services like Firebase storage if required but custom claims can be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM