【问题标题】:Access user admin informations in Firebase (ReactJS / Firebase Custom Claims)在 Firebase 中访问用户管理信息(ReactJS / Firebase 自定义声明)
【发布时间】:2020-12-05 07:29:24
【问题描述】:

我正在对我的 react 应用程序使用 firebase 身份验证。在我的组件中,我使用以下内容:

renderUser() {
    const user = firebase.auth().currentUser;
    console.log(user);
    return (
      <div className="nav-actions-wrapper">
        {user ? (
          // Display post link here
          <section className="nav-actions">
            <a className="btn btn-primary mr-4" href="#" onClick={this.showPostShopPopup}>
              Admin Post
            </a>
            <PostShopPopup
              user={this.props.user}
              status={this.state.postShopPopupStatus}
              hidePopup={this.hidePostShopPopup}
            />
          </section>
        ) : (
          <section>
            <a className="btn btn-outline-primary" href="#" onClick={this.showPopup}>
              Log in
            </a>
            <LoginPopup status={this.state.popupStatus} hidePopup={this.hidePopup} />     
          </section>
        )}
      </div>
    );
  }

我添加了一个自定义函数,通过自定义声明将提供的电子邮件设置为 admin: true。它工作正常,现在当我 console.log(user) 时,我在列表中看到 admin: true。

现在我怎样才能访问它以便我可以做{user.admin? ...: ...}?因为现在,当我这样做时,即使在控制台日志中它被标记为 admin: true...

【问题讨论】:

  • 你能分享这个console.log(user);的结果吗?
  • 它返回一个对象,其中包含有关用户的所有信息(email、emailVerified、photoURL 等以及一些其他不可读的对象和数组,包含奇怪的字母和东西)

标签: javascript reactjs firebase firebase-authentication


【解决方案1】:

首先在你的 node js 服务器中运行这个 sn-p。

创建一个 GET 端点并仅发送一个简单的 http 请求,以便运行并为您想要成为管理员的给定用户 ID 创建一个自定义令牌(在 Firebase 令牌的 customClaims 字段中添加角色:'admin')。

Node.js:

admin.auth().setCustomUserClaims(${UID}, {admin: true}).then(claims => 
    console.log(`CUSTOM CLAIMS ADDED: ${claims}`))

客户端(在我的情况下是有角度的但逻辑是一样的,创建一个服务函数)

您想要来自身份验证模块的 idTokenResult 对象

async isAdmin() {
    const { claims } = await firebase.auth().currentUser.getIdTokenResult()
    return claims?.admin == true ? true || false
}

这会返回一个布尔值。

【讨论】:

    【解决方案2】:

    自定义声明不能在 User 对象中直接访问,供您立即使用。您将不得不在 User 对象上调用 getIdTokenResult() 以获取声明。请注意,它异步返回一个承诺并产生一个IdTokenResult 对象。此对象包含您要查找的 claims。

    【讨论】:

    • 它只是带来了另一个问题,现在我的onlick={this.showPostPopup} 带来了以下错误:Cannot read property 'showPostShopPopup' of undefined。我已经尝试在我的构造函数中绑定它,但它仍然抛出错误
    • 如果您有新问题,请将其单独发布并说明现在无法按您预期的方式工作。
    猜你喜欢
    • 2021-01-24
    • 2017-09-05
    • 2020-06-29
    • 1970-01-01
    • 2020-09-18
    • 2020-01-30
    • 2020-08-19
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多