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

Google API令牌刷新报错invalid_grant,寻求排查方案

Google Drive API令牌刷新invalid_grant错误排查方案

问题描述

之前正常运行的Python Google Drive API脚本,现在令牌刷新时抛出错误:

google.auth.exceptions.RefreshError: ('invalid_grant: Bad Request', {'error': 'invalid_grant', 'error_description': 'Bad Request'})

且脚本未触发重新登录提示,重新生成凭证JSON文件后问题依旧,个人项目不确定是否需要切换到生产环境。

原初始化代码:

def create_service(credentials, api_name, api_version, *scopes):
    print("-"*100)
    print("Data: ", credentials, api_name, api_version, scopes, sep='-')
    CREDENTIALS = credentials
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]
    print("Scopes: ", SCOPES)
    
    token_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.json'
    
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(token_file):
        creds = Credentials.from_authorized_user_file(token_file, SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    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(
                CREDENTIALS, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(token_file, 'w') as token:
            token.write(creds.to_json())

    try:
        service = build(API_SERVICE_NAME, API_VERSION, credentials=creds)
        print('Service created successfully')
        print("-"*100)
        return service
    except HttpError as error:
        # Handle errors from drive API.
        print(f'An error occurred: {error}')
    except Exception as error:
        print('Unable to connect.')
        print(error)
        return None

排查与修复思路

  • 删除旧令牌文件:直接删除脚本生成的token_{API_SERVICE_NAME}_{API_VERSION}.json文件(比如token_drive_v3.json),旧文件中的refresh_token已失效,脚本当前逻辑会优先尝试刷新而非触发重新授权,删除后会强制走首次登录流程生成新令牌。
  • 添加刷新异常捕获逻辑:修改代码中令牌刷新的分支,捕获RefreshError并强制触发重新授权,避免脚本卡在刷新失败的状态:
    if creds and creds.expired and creds.refresh_token:
        try:
            creds.refresh(Request())
        except google.auth.exceptions.RefreshError:
            os.remove(token_file)
            creds = None
    
    这样刷新失败时会删除旧令牌,让脚本进入重新登录分支。
  • 确认凭证与OAuth配置:
    • 确保创建的是桌面应用类型的OAuth凭证,与脚本使用的InstalledAppFlow匹配;
    • 个人项目无需切换到生产环境,保持测试环境即可,但要在OAuth同意屏幕中添加你的Google账号作为测试用户;
  • 检查账号状态:如果近期修改过Google账号密码、开启/关闭2FA,或者更换了登录设备,旧refresh_token会直接失效,必须重新授权;
  • 验证作用域一致性:确保代码中使用的Scopes与创建凭证时选择的完全一致,作用域不匹配会导致令牌刷新失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:53:27