使用Google API Python触发ValueError:授权用户信息格式不符
解决Google API授权格式错误问题
问题场景
创建Desktop App类型的OAuth Client ID并下载对应JSON文件后,运行Python代码调用Google API时出现以下错误:
Traceback (most recent call last): creds = Credentials.from_authorized_user_file('credent.json', SCOPES) File "C:\Users\WINDOWS\AppData\Local\Programs\Python\Python310\lib\site-packages\google\oauth2\credentials.py", line 440, in from_authorized_user_file return cls.from_authorized_user_info(data, scopes) File "C:\Users\WINDOWS\AppData\Local\Programs\Python\Python310\lib\site-packages\google\oauth2\credentials.py", line 390, in from_authorized_user_info raise ValueError( ValueError: Authorized user info was not in the expected format, missing fields client_secret, client_id, refresh_token.
下载的JSON文件内容:
{"installed": {"client_id": "client_id_my", "project_id": "projectname123", "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": "SECRET", "redirect_uris": ["http://localhost"]} }
移除"installed"字段后,错误变为:
ValueError: Authorized user info was not in the expected format, missing fields refresh_token.
使用的Python代码:
import os.path from google.oauth2.credentials import Credentials SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly'] creds = Credentials.from_authorized_user_file('credent.json', SCOPES)
问题原因
Credentials.from_authorized_user_file() 方法读取的是用户授权后生成的包含refresh_token的凭证文件,而你当前使用的是OAuth客户端配置文件(即下载的带installed字段的JSON),两者格式完全不同,因此会提示缺少必要字段。
解决步骤
你需要通过授权流程生成符合要求的用户凭证文件,修改代码如下:
import os.path from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly'] def get_credentials(): 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 = InstalledAppFlow.from_client_secrets_file( 'credent.json', SCOPES) creds = flow.run_local_server(port=0) # 保存凭证供下次使用 with open('token.json', 'w') as token: token.write(creds.to_json()) return creds # 获取凭证并使用 creds = get_credentials()
说明
- 运行修改后的代码,会自动弹出浏览器引导你完成Google账号授权
- 授权成功后,代码会在当前目录生成
token.json文件,这个文件就是Credentials.from_authorized_user_file()需要的格式,包含refresh_token等必要字段 - 不要修改原始的
credent.json客户端配置文件,它仅用于初始化授权流程
内容的提问来源于stack exchange,提问作者Azazel
相关产品推荐
相关产品推荐

