首页 > 解决方案 > 从 Firebase 管理员向客户端发送自定义令牌

问题描述

我正在使用适用于 Nodejs 的 Firebase Admin SDK,以便我可以创建自定义令牌以在 iOS 设备中进行身份验证。在 Nodejs 文档中,它声明您在创建令牌后将其发送回客户端。

let uid = 'some-uid';

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

我的问题是最有效的方法。我一直在考虑创建可能函数以将其发送回响应正文,但我觉得我可能想多了。这是推荐的方法还是我缺少一种更简单的方法?

标签: javascriptnode.jsfirebasefirebase-admin

解决方案


这是我的应用程序(云功能)中的工作代码,就像复制粘贴一样简单,供您参考。

exports.getCustomToken = functions.https.onRequest(async (req, res) => {
    return cors(req, res, async () => {
        try {
                const token = await createCustomToken(req.body.uid);
                return res.json(token);
        
        } catch (error) {
            res.status(500).json({ message: 'Something went wrong' });
        }
    });
});

async function createCustomToken(userUid, role = '') {

       let createdCustomToken = '';

        console.log('Ceating a custom token for user uid', userUid);
        await firebaseAdmin.auth().createCustomToken(userUid)
            .then(function (customToken) {
                // Send token back to client
                console.log('customToken is ', customToken)
                createdCustomToken = customToken;
            })
            .catch(function (error) {
                console.log('Error creating custom token:', error);
            });
    
         return createdCustomToken;
}

推荐阅读