Firebase 自定义声明如何设置? [英] Firebase custom claim how to set?

查看:28
本文介绍了Firebase 自定义声明如何设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 firebase 自定义声明而苦苦挣扎.

I'm struggling with firebase custom claims.

我测试了很多方法都没有用.显然,我错过了概念本身的一些重要内容.

I have tested a lot of approaches nothing works. Obviously, I miss something important in the concept itself.

所以我回到了根源.来自 google 示例的此脚本应该对新创建的用户应用海关规则

So I'm back to the root. This script from the google example should apply customs rule on a newly created user

exports.processSignUp = functions.auth.user().onCreate(event => {
  const user = event.data; // The Firebase user.
  const customClaims = {
      param: true,
      accessLevel: 9
    };
  // Set custom user claims on this newly created user.
  return admin.auth().setCustomUserClaims(user.uid, customClaims)   

});

然后在客户端上,我用

firebase.auth().currentUser.getIdTokenResult()
                .then((idTokenResult) => {
                    // Confirm the user is an Admin.
                    console.log(idTokenResult.claims)
                    if (!!idTokenResult.claims.param) {
                    // Show admin UI.
                    console.log("param")
                    } else {
                    // Show regular user UI.
                    console.log("no param")
                    }
                })
                .catch((error) => {
                    console.log(error);
                });

只是原始复制粘贴的所有内容仍然不起作用.我已经在本地机器上进行了测试(cors 可能有问题?)并已部署

Everything just a raw copy-paste still doesn't work. I've tested both from the local machine(there could be troubles with cors?) and deployed

推荐答案

这是一个竞争情况.如果Function先结束,你会得到更新的数据.

This is a race situation. If the Function end first then, you will get the updated data.

getIdTokenResult 方法确实会强制刷新,但如果自定义声明尚未准备好,则毫无意义.

The getIdTokenResult method does force refresh but if the custom claim is not ready then, it is pointless.

您需要设置另一个数据控制结构来触发客户端上的强制刷新.以rtd的实时监听器为例;

You need to set another data control structure to trigger the force refresh on the client. By example a real-time listener to the rtd;

root.child(`permissions/${uid}`).on..

侦听器内部的逻辑是:如果该节点的值存在并且是大于某个阈值的数字,则触发用户身份验证刷新

在此期间,如果没有数据快照,则 ui 可以反映加载状态,如果数据快照存在但权限级别较低,则用户界面可以反映非管理员视图.

During that time the ui can reflect a loading state if there is no datasnapshot or the not admin view if the datasnapshot exists but is a lower permission level.

在函数中,您必须在设置声明后设置节点:

In Functions you have to set the node after the claim is set:

..setCustomUserClaims(..).then(
    ref.setValue(9)
);

我有一个关于 pastebin

这篇关于Firebase 自定义声明如何设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆