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
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) {}
});
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