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

如何在Firebase Cloud Functions(Python)中启用身份验证要求

解决Firebase Python云函数默认公开及限制Cloud Shell调用的问题

问题原因

Firebase 2nd Gen(使用firebase_functions库)的HTTPS函数默认配置为允许所有用户调用,和1st Gen默认要求认证的行为不同,所以部署后会成为公开端点。

解决方案

要实现未认证访问返回权限拒绝,且仅允许Cloud Shell调用,可通过IAM权限配置结合代码身份验证的方式实现:

方法一:通过IAM限制调用权限

这是最直接的方式,通过Google Cloud控制台配置函数的访问权限:

  • 打开Google Cloud控制台,进入「Cloud Functions」页面,找到你的hello_world函数
  • 切换到「权限」标签,移除默认的allUsers和allAuthenticatedUsers权限条目(如果存在)
  • 点击「添加权限」,输入Cloud Shell使用的默认服务账号邮箱:[你的项目ID]@cloudservices.gserviceaccount.com
  • 为该账号分配「Cloud Functions Invoker」角色,保存配置

完成后,只有该服务账号能调用函数,未认证或其他账号访问会直接返回403权限拒绝。

方法二:代码中添加身份验证逻辑(可选,双重保障)

如果需要更细粒度的控制,或避免IAM配置失误,可在代码中验证请求的身份令牌。Cloud Shell调用时使用的是Google服务账号令牌,需用google-auth库验证:

首先安装依赖:

pip install google-auth

修改函数代码:

from firebase_functions import https_fn
import google.auth
from google.oauth2 import id_token
from google.auth.transport import requests

PROJECT_ID = "你的项目ID"

@https_fn.on_request(region="europe-west1") 
def hello_world(req: https_fn.Request) -> https_fn.Response:
    # 检查Authorization头
    auth_header = req.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return https_fn.Response("权限拒绝:未提供有效令牌", status=403)
    
    token = auth_header.split('Bearer ')[1]
    try:
        # 验证服务账号令牌
        decoded_token = id_token.verify_oauth2_token(token, requests.Request(), audience=PROJECT_ID)
        # 限制仅允许Cloud Shell默认服务账号调用
        if decoded_token['email'] != f"{PROJECT_ID}@cloudservices.gserviceaccount.com":
            return https_fn.Response("权限拒绝:无调用权限", status=403)
        
        return https_fn.Response(f"Hello {decoded_token.get('email')}")
    except Exception as e:
        return https_fn.Response(f"权限拒绝:无效令牌 - {str(e)}", status=403)

调用方式(Cloud Shell中)

在Cloud Shell中调用函数时,需先获取服务账号令牌,再发起请求:

# 获取访问令牌
TOKEN=$(gcloud auth print-identity-token)
# 调用函数,替换为你的函数URL
curl -H "Authorization: Bearer $TOKEN" https://europe-west1-[你的项目ID].cloudfunctions.net/hello_world

内容的提问来源于stack exchange,提问作者Luca Köster

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:55:03