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

如何为Google Cloud Function(Gen2, Python3.11)配置专属访问权限

Google Cloud Gen2云函数认证设置及多端实现

一、取消未认证访问权限

重新部署云函数,移除--allow-unauthenticated参数,确保只有授权请求能访问:

gcloud beta functions deploy function_name --region=us-central1 --source=src --runtime=python311 --gen2 --entry-point=main --memory=512Mb --min-instances=1 --max-instances=100 --timeout=120s --trigger-http --cpu=1 --concurrency=100

二、认证方案选择

推荐使用Google ID Token验证,适合面向用户的iOS/Web应用:通过用户登录获取合法Token,云函数验证Token有效性后处理请求,兼顾安全性和易用性。

三、云函数端(Python)添加验证逻辑

修改函数代码,加入ID Token校验逻辑:

import functions_framework
import google.auth
from google.oauth2 import id_token
from google.auth.transport import requests

@functions_framework.http
def main(request):
    # 提取Authorization头中的Token
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return 'Unauthorized', 401
    
    id_token_str = auth_header.split('Bearer ')[1]
    
    try:
        # 替换为你的云函数受众地址(格式:https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME)
        audience = 'https://us-central1-your-project-id.cloudfunctions.net/function_name'
        # 验证Token合法性
        id_info = id_token.verify_oauth2_token(id_token_str, requests.Request(), audience)
        
        # 可选:添加用户权限校验,比如限制特定邮箱/域名访问
        # if not id_info['email'].endswith('@yourdomain.com'):
        #     return 'Forbidden', 403
        
        # 处理业务逻辑
        return 'Request processed successfully', 200
    except ValueError as e:
        # Token无效时返回未授权
        return f'Unauthorized: {str(e)}', 401

四、iOS端(Swift)实现认证请求

假设已集成Google Sign-In SDK,获取ID Token后携带到请求头:

import GoogleSignIn
import Foundation

// 获取当前登录用户的ID Token
func fetchIDToken(completion: @escaping (String?) -> Void) {
    guard let currentUser = GIDSignIn.sharedInstance.currentUser else {
        completion(nil)
        return
    }
    currentUser.refreshTokensIfNeeded { user, error in
        completion(user?.idToken?.tokenString)
    }
}

// 调用云函数
func invokeCloudFunction() {
    fetchIDToken { token in
        guard let idToken = token else {
            print("Failed to retrieve ID Token")
            return
        }
        guard let url = URL(string: "https://us-central1-your-project-id.cloudfunctions.net/function_name") else {
            print("Invalid function URL")
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST" // 根据实际请求方法调整
        request.setValue("Bearer \(idToken)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        // 添加请求体(按需)
        let requestBody = ["param1": "value1"]
        request.httpBody = try? JSONSerialization.data(withJSONObject: requestBody)
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Request error: \(error.localizedDescription)")
                return
            }
            if let data = data, let responseStr = String(data: data, encoding: .utf8) {
                print("Function response: \(responseStr)")
            }
        }.resume()
    }
}

五、Web端(JavaScript + axios)实现认证请求

假设已集成Google Sign-In,获取ID Token后通过axios发送请求:

// 获取当前用户的ID Token
async function getIDToken() {
  const authInstance = gapi.auth2.getAuthInstance();
  const user = authInstance.currentUser.get();
  const authResponse = await user.getAuthResponse();
  return authResponse.id_token;
}

// 调用云函数
async function callCloudFunction() {
  try {
    const idToken = await getIDToken();
    const response = await axios({
      method: 'post', // 匹配云函数的请求方法
      url: 'https://us-central1-your-project-id.cloudfunctions.net/function_name',
      headers: {
        'Authorization': `Bearer ${idToken}`,
        'Content-Type': 'application/json'
      },
      data: { param1: 'value1' } // 请求体(按需)
    });
    console.log('Function response:', response.data);
  } catch (err) {
    console.error('Request failed:', err.response?.data || err.message);
  }
}

六、可选:IAM粒度权限控制

如果需要更严格的访问控制,可在Google Cloud控制台给特定账号添加Cloud Functions Invoker角色:

  • 进入云函数详情页,切换到「权限」标签
  • 点击「添加主账号」,输入用户邮箱或服务账号邮箱
  • 选择角色「Cloud Functions > Cloud Functions Invoker」并保存
  • 此时只有该账号生成的Token能通过验证访问函数

内容的提问来源于stack exchange,提问作者Mohammed Imthathullah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:34:55