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

Python脚本使用OAuth2登录YouTube后保存Credentials报错求助

YouTube OAuth2 登录脚本 KeyError: 'client_secret' 问题排查

问题背景

我是Python初学者,参考视频编写了一段使用OAuth2登录YouTube账号并保存Credentials的脚本,用于后续调用YouTube API管理频道。已将包含OAuth 2.0 Client ID的client_secrets.json放在脚本同目录,并在Google Console中为Web应用配置了授权重定向URI http://localhost:8080/,但浏览器登录成功后触发KeyError: 'client_secret'报错。

脚本代码

import os
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

credentials = None

# token.pickle stores the user's credentials from previously successful logins
if os.path.exists('token.pickle'):
    print('Loading Credentials From File...')
    with open('token.pickle', 'rb') as token:
        credentials = pickle.load(token)

# If there are no valid credentials available, then either refresh the token or log in.
if not credentials or not credentials.valid:
    if credentials and credentials.expired and credentials.refresh_token:
        print('Refreshing Access Token...')
        credentials.refresh(Request())
    else:
        print('Fetching New Tokens...')
        flow = InstalledAppFlow.from_client_secrets_file(
            'client_secrets.json',
            scopes=[
                'https://www.googleapis.com/auth/youtube'
            ]
        )

        flow.run_local_server(host='localhost', port=8080, prompt='consent',
                              authorization_prompt_message='')
        credentials = flow.credentials

        # Save the credentials for the next run
        with open('token.pickle', 'wb') as f:
            print('Saving Credentials for Future Use...')
            pickle.dump(credentials, f)

报错信息

Fetching New Tokens...

Traceback (most recent call last):
  File "D:\youtube API\OAuthTest.py", line 29, in <module>
    flow.run_local_server(host='localhost', port=8080, prompt='consent',
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\google_auth_oauthlib\flow.py", line 511, in run_local_server
    self.fetch_token(authorization_response=authorization_response)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python310\lib\site-packages\google_auth_oauthlib\flow.py", line 298, in fetch_token
    kwargs.setdefault("client_secret", self.client_config["client_secret"])
KeyError: 'client_secret'
[Finished in 9.9s]

解决方案

  • 确认OAuth客户端ID类型:你当前下载的client_secrets.json可能是Web应用类型,而InstalledAppFlow更适配**桌面应用(Desktop app)**类型的凭证。Web应用凭证的结构和桌面应用不同,会导致找不到client_secret字段。操作步骤:
    1. 进入Google Cloud Console的「API和服务」→「凭据」页面
    2. 删除现有错误的Client ID,重新创建桌面应用类型的OAuth客户端ID
    3. 下载新的client_secrets.json替换脚本目录下的原文件
  • 验证凭证文件结构:打开新下载的client_secrets.json,确认包含installed顶级字段,正确结构示例:
{
  "installed": {
    "client_id": "xxx.apps.googleusercontent.com",
    "project_id": "xxx",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_secret": "xxx",
    "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
  }
}
  • 重定向URI配置:桌面应用类型无需手动配置重定向URI,Google会自动适配http://localhost类地址;如果坚持使用Web应用类型,需确保http://localhost:8080/已添加到授权重定向URI列表,同时确认脚本中run_local_server的端口和配置一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:05:28