Python云函数用JSON凭证访问Google Shared Drive遇refresh_token缺失问题
问题场景与错误
- 需求:Python云函数访问要求域内用户账号的Google共享云端硬盘,无法使用服务账号
- 操作:按桌面应用凭证文档获取含
installed字段的JSON客户端凭证,移除外层installed结构后调用Credentials.from_authorized_user_file - 报错:
google.auth.exceptions.RefreshError: ('invalid_request: Missing required parameter: refresh_token', {'error': 'invalid_request', 'error_description': 'Missing required parameter: refresh_token'})
错误根源
Credentials.from_authorized_user_file的作用是加载已完成OAuth2授权的用户令牌文件,而你使用的client_secrets.json是客户端身份配置文件——仅用于发起授权请求,本身不包含refresh token,因此无论是否修改外层结构都无法直接使用。
解决方法
1. 恢复原客户端凭证结构
把之前删除的installed外层结构加回去,原JSON格式是标准的桌面应用客户端凭证,不能修改。
2. 本地生成含refresh token的授权令牌文件
由于云函数无法弹出授权页面,需先在本地运行临时代码完成OAuth2授权:
from google_auth_oauthlib.flow import InstalledAppFlow import json # 定义Drive访问权限范围,按需调整 SCOPES = ['https://www.googleapis.com/auth/drive'] # 加载客户端凭证 flow = InstalledAppFlow.from_client_secrets_file('client_secrets.json', SCOPES) # 启动本地授权服务器,弹出浏览器让域内账号登录授权 creds = flow.run_local_server(port=8080) # 将授权令牌保存为token.json with open('token.json', 'w') as f: f.write(json.dumps(creds.to_json()))
运行后用拥有目标共享云端硬盘访问权限的域内账号登录授权,完成后会生成token.json,该文件包含refresh token、access token等必要授权信息。
3. 修改云函数代码
替换凭证加载逻辑,使用生成的token.json:
from google.oauth2.credentials import Credentials from googleapiclient.discovery import build def your_cloud_function_handler(event, context): # 加载授权令牌 creds = Credentials.from_authorized_user_file( 'token.json', ['https://www.googleapis.com/auth/drive'] ) # 构建Drive服务实例 service = build('drive', 'v3', credentials=creds) # 共享云端硬盘操作示例(需替换为你的业务逻辑) results = service.files().list(q="'你的共享硬盘ID' in parents").execute() items = results.get('files', []) # ...
注意事项
- 生成
token.json时必须使用目标域内账号登录,确保该账号有共享硬盘的访问权限。 - 上传云函数时,将
token.json、client_secrets.json与main.py放在同一目录,注意保护凭证不泄露。 - 令牌过期时,
Credentials会自动通过refresh token刷新,无需重新授权。
内容的提问来源于stack exchange,提问作者Benjamin DOUA
相关产品推荐
相关产品推荐

