How to separate user roles in firebase?

后端 未结 2 955
隐瞒了意图╮
隐瞒了意图╮ 2020-12-17 03:55

How do I add user role authentication in firebase android app? From what I see, firebase only has email and password authentication. I want to develop an android app that ha

相关标签:
2条回答
  • 2020-12-17 04:15

    You can add a roles node in the firebase database storing the user's uid and their role.

    "roles" : {
        "uid1" : "normal",
        "uid2" : "premium",
        "uid3" : "normal",
    }
    

    Then you can get the role value after the user is successfully signed in

    ref.child("roles").child(firebaseUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String role = dataSnapshot.getValue(String.class);
            // check role and replace fragment
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
    
    0 讨论(0)
  • 2020-12-17 04:23

    Firebase just launched support for role based access on any user via custom user claims on the ID token: https://firebase.google.com/docs/auth/admin/custom-claims

    You would define the premium access rule:

    {
      "rules": {
        "premiumContent": {
          ".read": "auth.token.role === 'premium'",
          ".write": "auth.token.role === 'premium'",
        }
      }
    }
    

    Set the user role with the Admin SDK:

    // Set admin privilege on the user corresponding to uid.
    admin.auth().setCustomUserClaims(uid, {role: 'premium'}).then(() => {
      // The new custom claims will propagate to the user's ID token the
      // next time a new one is issued.
    });
    

    This will propagate to the corresponding user's ID token claims.

    To parse it from the token on the client, you need to base64 decode the ID token's payload.

    You can upgrade/downgrade users as needed. They also provided a programmatic way to list all users if you have recurring scripts to change a users' access levels: https://firebase.google.com/docs/auth/admin/manage-users#list_all_users

    0 讨论(0)
提交回复
热议问题