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

Python中使用Google OAuth2服务账号无法模拟用户或获取Token

问题分析与修复方案

为什么token显示为None?

服务账号的Credentials对象在未实际发起API请求或手动刷新token之前,token属性默认就是None,这是正常行为,不是真正的问题根源。你无法获取文件列表的原因在于代码的其他错误。

代码中的具体问题及修复

  1. 缺少必要的导入
    代码中使用了build方法但未导入,需要添加:

    from googleapiclient.discovery import build
    
  2. 函数定义缺失导致逻辑未执行
    代码最后调用了main()但未定义该函数,导致核心的Drive API调用逻辑可能并未实际执行(或执行时出错但未被捕获)。需要将代码逻辑封装到main()函数中。

  3. 完善凭据的使用逻辑
    虽然客户端库会自动处理token刷新,但显式验证凭据有效性可以提前排查问题。

修复后的完整代码

from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def main():
    # 加载服务账号凭据并指定权限范围
    credentials = service_account.Credentials.from_service_account_file(
        'serviceaccount.json',
        scopes=['https://www.googleapis.com/auth/drive']
    )
    # 委派给目标域用户
    delegated_credentials = credentials.with_subject('someone@company.com')

    # 显式刷新凭据(客户端库通常会自动处理,手动刷新可提前验证)
    if not delegated_credentials.valid:
        delegated_credentials.refresh(Request())
    
    # 此时token已生成,可验证
    print(delegated_credentials.token)

    try:
        # 构建Drive服务并调用文件列表接口
        drive_service = build('drive', 'v3', credentials=delegated_credentials)
        results = drive_service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)"
        ).execute()
        items = results.get('files', [])

        if not items:
            print('没有找到文件。')
            return
        print('文件列表:')
        for item in items:
            print(f"{item['name']} ({item['id']})")
    except HttpError as error:
        print(f"发生API错误:{error}")

if __name__ == '__main__':
    main()

额外检查项

  • 确认服务账号已在Google Workspace Admin控制台中启用域范围委派,且已添加https://www.googleapis.com/auth/drive权限范围
  • 确认目标用户someone@company.com是你的Workspace域内的有效用户
  • 确认serviceaccount.json文件路径正确,文件内容无损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:45:35