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

查看:200
本文介绍了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

推荐答案

这是比赛情况.如果该函数先结束,那么您将获得更新的数据.

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..

并且侦听器内部的逻辑为:if the value for that node exists and is a number greater than some threshold, then trigger the user auth refresh

And the logic inside the listener would be: if the value for that node exists and is a number greater than some threshold, then trigger the user auth refresh

在此期间,如果没有datasnapshot,则ui可以反映加载状态;如果da​​tasnapshot存在,但权限级别较低,则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天全站免登陆