在Google Cloud Function中用Python访问指定用户Google Drive的认证问题
在GCP Cloud Function中用Python访问Workspace用户Drive文件夹的解决方案
核心思路
利用Workspace域宽委派让Cloud Function的默认服务账号模拟目标Workspace用户,无需本地密钥文件,直接在运行时获取带委派权限的凭证,进而调用Drive API读取指定文件夹内容。
前置配置步骤
- 启用域宽委派:
- 找到Cloud Function使用的默认服务账号(格式:
[你的项目ID]@appspot.gserviceaccount.com),在GCP IAM控制台开启该账号的"域宽委派"选项。 - 登录Workspace管理员控制台,进入「安全 > API控制 > 域宽委派」,添加上述服务账号的客户端ID,授权以下API范围(按需选择):
- 只读权限:
https://www.googleapis.com/auth/drive.readonly - 读写权限:
https://www.googleapis.com/auth/drive
- 只读权限:
- 找到Cloud Function使用的默认服务账号(格式:
- 启用Drive API:在GCP API库中搜索并启用「Google Drive API」。
Cloud Function代码实现
依赖文件(requirements.txt)
google-api-python-client>=2.100.0 google-auth>=2.23.0
主代码(main.py)
from google.auth import default from google.auth.transport.requests import Request from googleapiclient.discovery import build # 替换为你的目标用户邮箱和文件夹ID TARGET_USER = "user_name@domain.com" TARGET_FOLDER_ID = "xxxxxxxxx" def list_drive_files(request): # 获取Cloud Function默认服务账号凭证 creds, _ = default() # 模拟目标Workspace用户,添加委派权限 creds = creds.with_subject(TARGET_USER) creds.refresh(Request()) # 构建Drive API服务实例 drive_service = build('drive', 'v3', credentials=creds) # 查询指定文件夹下的所有文件 query = f"'{TARGET_FOLDER_ID}' in parents" results = drive_service.files().list( q=query, pageSize=100, fields="nextPageToken, files(id, name, mimeType)", includeItemsFromAllDrives=True, supportsAllDrives=True ).execute() files = results.get('files', []) if not files: return "目标文件夹中无文件" # 格式化返回结果 output = ["文件列表:"] for file in files: output.append(f"- {file['name']} | ID: {file['id']} | 类型: {file['mimeType']}") return "\n".join(output)
关键注意事项
- 无需将目标文件夹共享给服务账号:通过域宽委派模拟用户后,服务账号拥有该用户的Drive访问权限,只要用户能访问文件夹,服务账号即可读取。
- 权限最小化原则:优先使用
drive.readonly范围,避免过度授权。 - 测试验证:部署后可通过Cloud Function的测试功能触发,检查返回的文件列表是否正确。
内容的提问来源于stack exchange,提问作者Safiul Alam
相关产品推荐
相关产品推荐

