You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无客户端情况下验证Firebase Auth Token(Cloud Run服务端)

在Cloud Run中实现纯服务端Firebase认证方案

需求场景

需要为外部企业/服务器用户搭建纯服务端的Firebase认证流程,无需客户端安装Firebase SDK,核心流程如下:

  • 用户传入预先创建并存储在Firestore中的自定义密钥
  • 服务端验证密钥有效性后,返回可直接使用的Firebase令牌
  • 用户后续调用接口时,通过admin.auth().verifyIdToken(token)完成权限校验

前期尝试的问题

最初尝试使用createCustomToken生成自定义令牌:

admin.auth()
    .createCustomToken(uid)
    .then((customToken) => {
        console.log(customToken)
    })
    .catch((error) => {
        console.log('Error creating custom token:', error);
    });

但该方式要求客户端必须依赖Firebase SDK才能完成令牌转换,无法适配外部非Firebase客户端的需求。

解决方案

通过调用Firebase Identity Toolkit的公开API,将自定义令牌转换为标准的Firebase ID Token,无需客户端依赖任何Firebase工具:

admin.auth()
    .createCustomToken(uid)
    .then((customToken) => {
        console.log(customToken)

        axios.post('https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=你的Firebase项目API密钥', {
            "returnSecureToken": true,
            "token": customToken
        }).then((res) => {
           // 此处res.data.idToken即为可直接用于Cloud Run接口验证的有效令牌
        })
    })
    .catch((error) => {
        console.log('Error creating custom token:', error);
    });

接口权限验证

在受保护的Cloud Run接口中,使用以下代码完成令牌校验:

const verifiedToken = await admin.auth().verifyIdToken(token);

内容的提问来源于stack exchange,提问作者Joe Alvini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:15:36