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

调用Google Cloud language_v1 API报401未认证错误原因咨询

问题现象

调用Google Cloud Language v1 API时抛出401未认证错误:

google.api_core.exceptions.Unauthenticated: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.

对应实现代码:

from google.cloud import language_v1
from google.oauth2 import service_account

SCOPES = 'https://www.googleapis.com/auth/cloud-language'
SERVICE_ACCOUNT_FILE = 'service_account.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = language_v1.LanguageServiceClient(credentials=credentials)
type_ = language_v1.Document.Type.PLAIN_TEXT
language = "en"
text = "I love life!"
document = {"content": text, "type_": type_, "language": language}
encoding_type = language_v1.EncodingType.UTF8
response = client.analyze_sentiment(request={'document': document, 'encoding_type': encoding_type})
score = response.document_sentiment.score
print(score)

已完成的前置排查项:

  • 确认服务账号持有API调用所需的必要权限
  • 确认服务账号密钥文件包含私钥等必填配置项
可能的触发原因

按出现概率从高到低排序:

  • Scope参数类型错误:代码中SCOPES定义为单个字符串,但service_account.Credentials.from_service_account_file方法的scopes参数要求传入字符串列表。传入单个字符串时,方法会遍历字符串的每个字符作为独立scope,最终生成的凭证没有携带合法的API访问权限范围,直接触发认证失败,是这段代码最明显的问题。
  • 本地系统时钟偏差过大:OAuth2访问令牌有严格的时间有效性校验,如果本地设备时间和Google授权服务器时间差超过5分钟,生成的令牌会被判定为过期/无效,抛出401错误。
  • 项目层未启用目标API:即使服务账号本身权限配置正确,如果所属GCP项目没有启用Cloud Natural Language API,请求会被认证层拦截,这类场景下经常返回401而非预期的403错误。
  • 服务账号密钥状态异常:仅检查密钥文件包含私钥字段不足以确认密钥可用,若密钥已在控制台被管理员吊销、删除,或者服务账号本身被禁用,即使文件结构完整也无法通过认证。
  • 本地环境配置冲突:如果本地配置了GOOGLE_APPLICATION_CREDENTIALS环境变量指向其他无效密钥,或者配置了API端点覆写、全局请求代理等环境变量,可能会覆盖代码中显式传入的凭证配置,导致实际请求使用的认证信息无效。
修复参考

优先修正scope参数的类型问题,调整后的核心代码如下:

# scopes必须传入列表类型,即使只需要配置单个权限
SCOPES = ['https://www.googleapis.com/auth/cloud-language']
SERVICE_ACCOUNT_FILE = 'service_account.json'
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE,
    scopes=SCOPES
)

修正scope后如果仍报错,按顺序核对本地时间是否同步、目标API是否已在对应项目启用、服务账号及对应密钥是否处于启用状态、本地是否存在冲突的环境变量配置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 07:48:32