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

Gmail API认证时出现URI不匹配404错误求助

Gmail API认证遇URI不匹配404错误问题

调用以下Python代码中的gmail_authenticate()函数进行Gmail API认证时,出现URI不匹配的404错误。已在Google云控制台添加回调URI,但问题仍未解决。

相关代码

def gmail_authenticate():
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)

    # 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_path, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    # Build the Gmail service, Connect to the Gmail API
    service = build('gmail', 'v1', credentials=creds)
    return service

Google云控制台配置截图

Google云控制台OAuth回调URI配置

解决方法

  • 纠正OAuth客户端类型:代码中使用run_local_server(port=0)属于桌面应用认证流程,你当前配置的是网页应用类型的回调URI,两者不兼容。需要在Google云控制台重新创建桌面应用类型的OAuth客户端ID,该类型无需手动填写回调URI,系统会自动适配localhost随机端口。
  • 清理旧凭据:删除本地的token.pickle文件,旧凭据是基于错误的客户端配置生成的,必须清除后重新运行认证流程。
  • 替换密钥文件:确保代码中credentials_path指向新创建的桌面应用对应的credentials.json文件,不要继续使用旧的网页应用密钥文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:05:02