企业组织内调用Google API访问共享Google Drive的Sheets数据如何实现
企业组织内部Google Drive的Google Sheets Python访问解决方案
核心问题为当前使用的服务账号未纳入你的企业Google Workspace组织管理,被安全规则判定为外部主体,无法获得共享权限,以下为3种可行解决方案:
方案1:为现有服务账号开启全域权限委派
- 联系企业Google Workspace管理员,在Admin后台将你的服务账号添加为组织信任实体,同时开启全域权限委派功能
- 开启后可在代码中直接模拟有目标表格访问权限的组织内部用户身份鉴权,无需单独给服务账号共享表格
- 代码仅需修改
create_credentials函数,新增模拟用户配置即可:
def create_credentials(): credentials = Credentials.from_service_account_file( json_key, scopes=scopes) # 新增行:替换为已有表格访问权限的组织内部用户邮箱 credentials = credentials.with_subject("org_internal_user@your-company-domain.com") return gspread.authorize(credentials)
方案2:改用OAuth桌面应用鉴权模式
- 无需管理员配合,放弃服务账号鉴权,改用个人组织账号的OAuth凭证授权,鉴权身份为你本人的组织账号,天然符合内部权限规则
- 操作步骤:
- 在Google Cloud控制台同项目下,创建「桌面应用」类型的OAuth 2.0客户端ID,下载对应json凭证文件
- 调整鉴权逻辑,首次运行时弹出浏览器用你的组织账号授权即可,后续会自动缓存token无需重复登录
- 对应代码示例:
from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import pickle import os def create_credentials(): creds = None # 本地缓存已授权的token if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( '你下载的OAuth凭证文件.json', scopes) creds = flow.run_local_server(port=0) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) return gspread.authorize(creds)
方案3:创建归属组织的内部服务账号
- 申请在企业绑定的Google Cloud组织节点下创建服务账号,该类服务账号会被判定为组织内部实体,不会触发外部共享限制,直接给该服务账号授予表格访问权限即可沿用原有代码正常运行。
内容的提问来源于stack exchange,提问作者RCarmody
相关产品推荐
相关产品推荐

