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

Python调用Google OAuth2出现redirect_uri_mismatch 400错误求助

问题原因与解决方案

问题根源

你的credentials.json是Web应用类型的OAuth凭据,但代码中使用了InstalledAppFlow.run_local_server()方法——这个方法是专门为桌面/本地应用设计的,会自动生成http://localhost:随机端口作为重定向URI,完全忽略你在配置文件和Google控制台中设置的https://example.com/,因此导致重定向URI不匹配的400错误。

解决方案

根据你的实际应用场景,选择以下两种修复方式:

场景1:开发Web应用(需使用https://example.com/作为重定向)

替换InstalledAppFlow为通用的Flow类,手动指定重定向URI,并处理Web应用的授权码流程:

from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import Flow  # 替换InstalledAppFlow为Flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/documents.readonly']
DOCUMENT_ID = '13GMqNrDu604Cd8U_N5E6gPkL9rSJZSgRSDZHtg16Kao'

def test():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            # 使用Flow类并手动指定重定向URI
            flow = Flow.from_client_secrets_file(
                'credentials.json',
                scopes=SCOPES,
                redirect_uri='https://example.com/'
            )
            # 生成授权URL
            auth_url, state = flow.authorization_url(
                access_type='offline',
                include_granted_scopes='true'
            )
            print(f"请访问此URL完成授权: {auth_url}")
            # 实际Web应用中,需通过路由接收回调的code,此处为示例输入
            authorization_response = input("请粘贴授权后的完整回调URL: ")
            flow.fetch_token(authorization_response=authorization_response)
            creds = flow.credentials
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('docs', 'v1', credentials=creds)
        document = service.documents().get(documentId=DOCUMENT_ID).execute()
        print('文档标题: {}'.format(document.get('title')))
    except HttpError as err:
        print(err)

注:实际Web开发中,需结合你使用的框架(如Flask/Django)创建专门的回调路由,自动获取授权码,而非手动输入。

场景2:本地测试用桌面应用

如果只是本地调试,不需要Web应用的重定向URI:

  1. 登录Google Cloud控制台,删除现有的Web应用类型凭据。
  2. 创建一个桌面应用类型的OAuth凭据。
  3. 下载新的credentials.json替换本地文件(桌面应用凭据无redirect_uris字段)。
  4. 保留原代码中的InstalledAppFlow.run_local_server()不变,此时生成的localhost重定向URI会被Google自动认可。

额外注意事项

  • 无论哪种场景,都要确保Google控制台的凭据类型与代码中使用的Flow类匹配。
  • 修复前请删除本地的token.json,让程序重新触发完整的授权流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:32:49