【问题标题】:Firebase custom user claims are not set未设置 Firebase 自定义用户声明
【发布时间】:2020-09-08 14:14:51
【问题描述】:

我正在尝试在用户注册后添加自定义用户声明,以定义用户角色,使用 setCustomUserClaims

/api/users/addUser.js

export default async (req, res) => {
  const { displayName, email, password, role } = req.body;

  if (!displayName || !password || !email || !role) {
    return res.status(400).send({ message: 'Missing fields' });
  }

  try {
    const { uid } = await admin.auth().createUser({
      displayName,
      email,
      password,
    });
    await admin.auth().setCustomUserClaims(uid, role);
    res.status(201).send(uid);
  } catch (error) {
    handleError(res, error);
  }
};

此代码检查身份验证状态的任何更改并将 user 设置为当前登录的用户:

/utils/use-auth.js

useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
      } else {
        setUser(false);
        // Router.push('/login');
      }
    });

在我的 /pages/user/home,jsx

import { useAuth } from '../../utils/use-auth';

function home() {
  const { user } = useAuth();

  return (
    <div>
      <pre>{JSON.stringify(user, null, 4)}</pre>
        <AdminLayout componentProps={{ selected: '1' }} Component={HomeContent} />
    </div>
  );
}

显示的对象没有任何自定义声明。 当我检查firebase控制台时,我发现实际上添加了用户。

【问题讨论】:

  • 你是如何检查它们是否传播的?客户端只有在刷新其 ID 令牌后才能看到更新的声明,这会每小时自动发生一次,或者当您强制刷新时。
  • @FrankvanPuffelen 实际上我没有清楚地解释这个问题,我的意思是他们没有得到设置
  • 这里没有足够的信息。请将问题编辑为:1)检查错误并显示任何错误消息,2)清楚地说明您要设置的声明,3)解释您如何观察到代码未按您预期的方式工作。我建议阅读:stackoverflow.com/help/minimal-reproducible-example
  • @DougStevenson 我添加了更多细节
  • 那么您观察到的究竟是什么表明未设置声明?您是否期待JSON.stringify(user, null, 4)} 以某种方式显示这一点?有一个用于从用户对象访问自定义声明的特定 API - 请改用它。

标签: javascript firebase firebase-authentication firebase-admin


【解决方案1】:

尝试使用

admin.auth().setCustomUserClaims(uid, claims).then(() => {
// Do your stuff here
});

并验证类似的声明

admin.auth().verifyIdToken(idToken).then((claims) => {
// check claims
  if (claims) { 
  // do your stuff here
  }
});

更多信息请查看https://firebase.google.com/docs/auth/admin/custom-claims#node.js

【讨论】:

  • 实际上,在我的 userRecord 对象中我找不到任何名为 customClaims 的字段
  • 您不会在用户对象中找到声明,而是在令牌中找到声明并验证上述声明
  • 您也可以查看客户的索赔。请查看firebase.google.com/docs/auth/admin/custom-claims#javascript
  • @AbdullahToufiq 我们是否也可以从客户端设置声明?
  • @UmairA。您可以访问声明,但不能从客户端设置声明
猜你喜欢
  • 2019-12-17
  • 2019-07-02
  • 1970-01-01
  • 2021-06-16
  • 2020-01-30
  • 2019-03-24
  • 1970-01-01
  • 2020-06-29
  • 2020-06-28
相关资源
最近更新 更多