管理员SDK自定义声明返回null

时间:2019-02-24 18:25:42

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

我在Android上使用Firebase云函数来创建具有自定义声明的用户,我已将自定义声明用作文档,但自定义声明= null:(

预先感谢

Firebase ID Token

代码:。

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);
        }
    });

})

1 个答案:

答案 0 :(得分:0)

您正在代码中创建自定义标记,而不是向现有标记添加声明。为此,请参见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脚本。