使用Python InstalledAppFlow调用Google Blogger API时出现OAuth 400错误(缺失redirect_uri)
问题原因及解决方案
你遇到的问题核心在于云端环境(Colab/Replit)与Desktop类型OAuth凭证的默认重定向逻辑不兼容,再加上你使用的google-auth-oauthlib 1.2.2版本可能存在自动读取重定向URI的bug,导致生成的授权URL缺失必填的redirect_uri参数。
直接修复代码
在调用authorization_url时显式指定redirect_uri为urn:ietf:wg:oauth:2.0:oob(这是Desktop凭证对应的"授权码手动输入"模式的标准URI):
import os from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build CLIENT_SECRET_FILE = 'credentials.json' SCOPES = ['https://www.googleapis.com/auth/blogger'] print("--- Starting Minimal Authentication Test ---") try: flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES) # 显式指定重定向URI auth_url, _ = flow.authorization_url(prompt='consent', redirect_uri='urn:ietf:wg:oauth:2.0:oob') print("\nPlease visit this URL to authorize:") print(auth_url) code = input('\nEnter the authorization code here: ') flow.fetch_token(code=code) creds = flow.credentials print("\nSUCCESS! Authentication credentials obtained.") except Exception as e: print(f"\n--- AN ERROR OCCURRED ---") print(e)
额外验证步骤
- 再次确认
credentials.json的格式,确保redirect_uris数组包含目标URI,结构如下:
{ "installed": { "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET", "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token" } }
- 若问题仍存在,尝试升级
google-auth-oauthlib到最新版本:
pip install --upgrade google-auth-oauthlib
适配Colab的更优方案
Colab提供了内置的认证工具,无需手动处理授权码流程,更适配云端环境:
from google.colab import auth from googleapiclient.discovery import build # 执行内置认证流程 auth.authenticate_user() # 直接构建Blogger服务 service = build('blogger', 'v3', credentials=None)
内容的提问来源于stack exchange,提问作者Carl Shop
相关产品推荐
相关产品推荐

