从 Firebase 管理员将自定义令牌发送回客户端

Sending Custom Tokens Back To Client From Firebase Admin

我正在使用适用于 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);
  });

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

此时我不会太担心效率。令牌很小,生成速度很快。要做的第一件事就是让它发挥作用。如果您愿意,可以使用 Cloud Functions,但 Admin SDK 可以在任何现代 nodejs 后端上运行。

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

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