【问题标题】:Admin Sdk custom claims return nullAdmin Sdk 自定义声明返回 null
【发布时间】:2019-07-18 04:47:14
【问题描述】:

我正在使用带有 android 的 firebase 云功能创建具有自定义声明的用户,我使用自定义声明作为文档,但自定义声明 = null : (

提前致谢

代码:。

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

const serviceAccount = require('../serviceAccountKey.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

exports.createSellerAccount = functions.https.onCall((data, context) => {
    const userEmail = data.email;
    const userPassword = data.password;

    return admin.auth().createUser({
        email: userEmail,
        password: userPassword
    }).then((userRecord) => {
        // See the UserRecord reference doc for the contents of userRecord.
        const additionalClaims = {
            premiumAccount: true
        };

        admin.auth().createCustomToken(userRecord.uid, additionalClaims)
            .then(function (customToken) {
                // Send token back to client
            })
            .catch(function (error) {
                console.log("Error creating custom token:", error);
            });

        return {
            sellerAccount: userRecord
        }
    }).catch((error) => {
        // console.log("Error creating new user:", error);
        if (error.code === "auth/email-already-exists") {
            throw new functions.https.HttpsError('already-exists', error.message);
        } else if (error.code === 'auth/invalid-email') {
            throw new functions.https.HttpsError('invalid-argument', error.message);
        } else {
            throw new functions.https.HttpsError('unknown', error.message);
        }
    });

})

【问题讨论】:

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


    【解决方案1】:

    您的代码创建了一个自定义令牌,而不是向现有令牌添加声明。要执行后者,请参阅包含此示例的 Set and validate custom user claims via the Admin SDK

    // Set admin privilege on the user corresponding to uid.
    
    admin.auth().setCustomUserClaims(uid, {admin: true}).then(() => {
      // The new custom claims will propagate to the user's ID token the
      // next time a new one is issued.
    });
    

    所以只需获取新用户的 UID 并使用它调用setCustomUserClaims。然后等待它传播到客户端,或者在节点脚本中记录令牌以确保声明在那里。

    请注意,我强烈建议您尝试隔离您的问题。不要在 Android 代码中显示令牌,而是将其记录在您的 Cloud Functions 代码中。更好的是,完全排除 Cloud Functions,只运行本地 Node.js 脚本。

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多