【问题标题】:How may I create custom claims in onCreate?如何在 onCreate 中创建自定义声明?
【发布时间】:2019-10-17 10:52:18
【问题描述】:

我正在使用 firebase 和 firebase 云功能。 当使用auth 创建用户时,我想根据他们的电子邮件设置自定义声明。我正在尝试使用functions.auth.user().onCreate(....) 来实现这一目标。

但是,当我尝试添加自定义声明时,我在控制台中收到以下错误:There is no user record corresponding to the provided identifier。

我已经在网上尝试了很多这样的例子,例如Google's docs 中的例子。 我还尝试在添加自定义声明之前手动创建用户,如下所示:

await auth().createUser({...user});
export const signupProcess = functions.auth.user().onCreate(async (user) => {

    // Check if user meets role criteria.
    const admin = (user.email && admins.has(user.email)? true: false);
    const customClaims = { admin };
    // Set custom user claims on this newly created user.
    return auth().setCustomUserClaims(user.uid, customClaims)
        .catch(error => {
            console.log(error);
        });
}); 

我希望通过正确的电子邮件访问管理员。 但是,我在创建用户时收到了描述的错误。

【问题讨论】:

  • auth() 的值是多少,因为您通常应该调用admin.auth().setCustomUserClaims()?
  • 另外,您使用哪个登录提供商来创建用户?
  • @RenaudTarnec Auth 是从 "firebase-admin" 导入的,'import { auth, initialiseApp, credentials } from "firebase-admin" :-) (抱歉格式化,只能访问 ios 应用程序)
  • 您使用的是firebase-functions 最新版本吗?一开始,你会尝试使用console.log('user.uid')进行调试吗?
  • @zkohi 我使用的是 2.3.0。我现在已经升级到 2.3.1。

标签: typescript firebase firebase-authentication google-cloud-functions


【解决方案1】:

我尝试了简单的代码。

我可以设置自定义用户声明。

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";

admin.initializeApp();

export const setCustomUserClaimsAdmin = functions.auth.user().onCreate(
  async (user: functions.auth.UserRecord): Promise<any> => {
    try {
      return admin.auth().setCustomUserClaims(user.uid, {
        ...user.customClaims,
        ...{ admin: true }
      });
    } catch (e) {
      console.error(e);
      return Promise.reject(e);
    }
  }
);

见https://github.com/zkohi/firebase-web-samples/tree/microsoft-oauth/functions。

您可以尝试简单的代码还是插入更多的调试代码?

【讨论】:

  • 谢谢你!该函数不记录任何错误。但是,我仍然无法访问为管理员保留的内容。但是,这可能是我的 firestore.rules 的问题。因此,不是这个问题的一部分。我将进一步调查此事件。
  • 再次感谢!原来,剩下的就是在客户端手动刷新令牌:-)
  • 我错了还是在这个例子中每个创建的用户都是管理员?
  • @FrancescoClementi 是的,你是对的。这是setCustomUserClaims() 示例。如果你想指定用户设置管理员,你应该在调用setCustomUserClaims()之前设置任何条件(例如邮件地址)。
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 2019-11-06
  • 1970-01-01
  • 2021-04-16
  • 2013-03-04
  • 2019-08-17
  • 1970-01-01
  • 2013-03-13
相关资源
最近更新 更多