从Android应用中获取自定义令牌在Firebase身份验证中。

huangapple go评论96阅读模式
英文:

Getting Custom tokens from Android App in Firebase Auth

问题

我正在开发一个需要使用 Firebase 自定义令牌的应用程序。
我可以通过 Node.js 服务器中的可调用云函数分配自定义声明。现在我需要在我的应用程序中使用它们来控制访问。我该如何实现它?

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

就像这样

我已经尝试从 Firestore 获取令牌,但会产生读取操作的成本。

英文:

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.

答案1

得分: 1

currentUser具有带有回调参数addOnSuccessListener的getIdToken方法addOnSuccessListener允许访问GetTokenResult(map)可用于检查您的声明

private fun login() {
    val user = FirebaseAuth.getInstance().currentUser
    if (user == null) showAuthActivity()
    user?.getIdToken(true) // forceRefresh: boolean 强制刷新令牌,不考虑令牌是否过期。
        ?.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("您没有权限使用此应用")
            }
        }
        ?.addOnFailureListener {
            showAuthActivity()
            showToast("出现问题,错误信息 = ${it.message}")
        }?.addOnCanceledListener {
            showAuthActivity()
        }
}
英文:

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()
            }
    }

答案2

得分: 1

使用<code>getIdToken()</code>方法获取认证用户的声明。

查看下面的示例:

user.getIdToken(false).addOnSuccessListener(new OnSuccessListener&lt;GetTokenResult&gt;() {
  @Override
  public void onSuccess(GetTokenResult result) {
    boolean isAdmin = result.getClaims().get(&quot;admin&quot;);
    if (isAdmin) {
      // 展示管理员界面。
      showAdminUI();
    } else {
      // 展示普通用户界面。
      showRegularUI();
    }
  }
});

另外请记住,在更新这些声明之前需要刷新 ID Token,你可以通过以下方式实现:

currentUser.getIdToken(true)

自定义声明仅用于验证角色和存储非常小的数据。不应将其用于保存用户信息。

来源和进一步阅读:https://firebase.google.com/docs/auth/admin/custom-claims#propagate_custom_claims_to_the_client

英文:

Use <code>getIdToken()</code> on Auth user to get claims.

Check out the below example:

user.getIdToken(false).addOnSuccessListener(new OnSuccessListener&lt;GetTokenResult&gt;() {
  @Override
  public void onSuccess(GetTokenResult result) {
    boolean isAdmin = result.getClaims().get(&quot;admin&quot;);
    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,

<code>currentUser.getIdToken(true)</code>

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

huangapple
  • 本文由 发表于 2020年10月9日 03:53:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64269704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定