访问Firebase中的用户管理信息(ReactJS/Firebase自定义声明)



我的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。它工作得很好,现在当我控制台.log(用户(时,我在列表中看到admin: true

现在,我如何访问它以便执行{user.admin? ...: ...}?因为现在,当我这样做时,它会抛出一个错误,说Cannot read property 'admin' of null,尽管在控制台日志中它被标记为admin: true。。。

自定义声明不能在User对象中直接访问以供您立即使用。您必须对User对象调用getIdTokenResult((才能获得声明。请注意,它异步返回一个promise并生成一个IdTokenResult对象。此对象包含您要查找的索赔。

首先在节点js服务器中运行这个片段。

创建一个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
}

这将返回一个布尔值。

最新更新