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

如何用Python从OAuth2平台获取access_token?unsupported_grant_type错误怎么解决

修复方案

核心问题原因

  • 认证参数重复传递:代码同时使用auth参数和请求体携带client_id、client_secret,两种认证方式混用导致Google OAuth2端点解析参数异常,无法正确读取grant_type的值,这是报错中grant_type显示为空的直接原因。
  • 缺失必填scope参数:Google的client_credentials授权流要求必须在请求体中指定scope参数,取值为你要访问的Google服务对应的权限范围,缺失该参数也会触发授权类型相关报错。

修复后代码示例

import requests

def token(self):
    client_id = ID_DO_CLIENTE
    client_secret = SECRET_TOKEN
    grant_type = 'client_credentials'
    # 替换为实际业务需要的权限范围,示例为Google云平台全局权限
    scope = 'https://www.googleapis.com/auth/cloud-platform'

    response = requests.post(
        "https://oauth2.googleapis.com/token",
        data={
            'grant_type': grant_type,
            'client_id': client_id,
            'client_secret': client_secret,
            'scope': scope
        }
    )
    print(response.text)

额外排查项

如果修改后仍存在报错,可按以下方向排查:

  1. 打印请求体原始内容,确认grant_type参数值为client_credentials,无拼写错误或空值
  2. 确认使用的client_id、client_secret是从Google Cloud控制台创建的有效OAuth2客户端凭证,且已开通客户端凭证授权流权限
  3. 确认scope参数取值和你要访问的Google服务权限要求一致,部分服务的客户端凭证流需要提前在云控制台配置对应访问权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:36:01