Snefru Clone
Snefru Clone

Reputation: 85

Getting Custom tokens from Android App in Firebase Auth

i am developing an application that requires firebase custom tokens. I can assign custom claims by callable cloud functions in node.js server. Now i need them in my app for controlling access. How can i achieve it?

FirebaseAuth.getInstance().getCurrentUser().getTokens()

like that

I have tried to get tokens from firestore but it costs read operations.

Upvotes: 0

Views: 572

Answers (2)

Sai
Sai

Reputation: 15738

currentUser has getIdToken method with a callback argument addOnSuccessListener. The addOnSuccessListener give access to GetTokenResult(map) use that to check your claims.

private fun login() {
        val user = FirebaseAuth.getInstance().currentUser
        if (user == null) showAuthActivity()
        user?.getIdToken(true) // forceRefresh: boolean Force refresh regardless of token expiration.
            ?.addOnSuccessListener {it: GetTokenResult ->
                val role = (it.claims["admin"] as? Boolean)
                    ?: (it.claims["clientUser"] as? Boolean) ?: false
                if (role) {
                    startActivity(Intent(this, MainActivity::class.java))
                    finish()
                } else {
                    showAuthActivity()
                    showToast("You don't have permissions to use this app")
                }
            }
            ?.addOnFailureListener {
                showAuthActivity()
                showToast("Something went wrong e = ${it.message}")
            }?.addOnCanceledListener {
                showAuthActivity()
            }
    }

Upvotes: 1

CaesarMyMate
CaesarMyMate

Reputation: 118

Use getIdToken() on Auth user to get claims.

Check out the below example:

user.getIdToken(false).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
  @Override
  public void onSuccess(GetTokenResult result) {
    boolean isAdmin = result.getClaims().get("admin");
    if (isAdmin) {
      // Show admin UI.
      showAdminUI();
    } else {
      // Show regular user UI.
      showRegularUI();
    }
  }
});

Also please keep in mind that ID Token need to be refreshed before these are updated which you can do by following,

currentUser.getIdToken(true)

And custom claims are only to verify roles and for storing very small data. It should not be used to keep user's information.

Source and Further Read: https://firebase.google.com/docs/auth/admin/custom-claims#propagate_custom_claims_to_the_client

Upvotes: 2

Related Questions