如何通过服务账号或自动OAuth授权Google Drive API并获取认证Token
Google Drive Changes Watch API 自动化认证方案(Python)
针对你需要无交互完成Google Drive Changes Watch API认证的需求,服务账号认证是最优方案,无需手动填写OAuth同意屏幕。以下是具体实现步骤:
一、前期准备
- 在Google Cloud控制台创建服务账号,下载对应的JSON密钥文件(命名为
service_account_key.json)。 - 启用Google Drive API,并为服务账号分配
https://www.googleapis.com/auth/drive或所需的细分权限(遵循最小权限原则)。 - 若需访问域内用户的Drive数据,需在Google Workspace管理控制台为服务账号开启域范围授权,指定要模拟的用户邮箱。
二、使用Google官方客户端库实现
1. 安装依赖
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
2. 代码示例
from google.oauth2 import service_account from googleapiclient.discovery import build import json # 定义权限范围与密钥文件路径 SCOPES = ['https://www.googleapis.com/auth/drive'] SERVICE_ACCOUNT_FILE = 'service_account_key.json' # 加载服务账号凭证,需模拟域内用户则添加subject参数(如subject='user@yourdomain.com') credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) # 构建Drive API客户端 drive_service = build('drive', 'v3', credentials=credentials) # 构造并发送Changes Watch请求 request_body = { "id": "4ba78bf0-6a47-11e2-bcfd-0800200c9a77", "type": "web_hook", "address": "https://www.example.com/notifications", "token": "target=myApp-myChangesChannelDest", "expiration": 1426325213000 } response = drive_service.changes().watch(body=request_body).execute() print(json.dumps(response, indent=2))
三、直接用requests库实现(不依赖客户端库)
1. 获取Bearer Token
import requests import json from google.oauth2 import service_account # 加载服务账号密钥 SERVICE_ACCOUNT_FILE = 'service_account_key.json' with open(SERVICE_ACCOUNT_FILE, 'r') as f: service_account_info = json.load(f) # 构造Token请求 token_url = "https://oauth2.googleapis.com/token" credentials = service_account.Credentials.from_service_account_info( service_account_info, scopes=['https://www.googleapis.com/auth/drive'] ) payload = { "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": credentials.to_jwt() } # 请求并提取Token token_response = requests.post(token_url, data=payload) access_token = token_response.json()['access_token']
2. 发送Changes Watch请求
watch_url = "https://www.googleapis.com/drive/v3/changes/watch" headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } request_body = { "id": "4ba78bf0-6a47-11e2-bcfd-0800200c9a77", "type": "web_hook", "address": "https://www.example.com/notifications", "token": "target=myApp-myChangesChannelDest", "expiration": 1426325213000 } response = requests.post(watch_url, headers=headers, json=request_body) print(json.dumps(response.json(), indent=2))
关键注意事项
- 服务账号拥有独立的Drive存储空间,若需访问个人用户Drive,必须通过域范围授权(仅适用于Google Workspace/Cloud Identity用户)。
- 确保Webhook接收地址
address可被Google服务器访问,首次创建watch时,Google会发送验证请求,需返回200状态码完成校验。
内容的提问来源于stack exchange,提问作者Tom3652
相关产品推荐
相关产品推荐

