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

Python调用需bearer token认证的私有API认证失败如何解决?

常见问题排查

  • 先确认Token请求端点是否正确:绝大多数OAuth2.0客户端模式的Token获取地址是独立端点,通常为/oauth2/token、/api/token等,不是你当前填写的通用API根路径,需核对API文档给出的专属Token请求地址。
  • 编码适配问题:部分服务商要求client_id和client_secret拼接后的字符串使用UTF-8编码,你当前使用的ISO-8859-1可尝试替换为UTF-8排查问题。
  • 缺少错误判断:先打印响应状态码可以快速定位问题:返回401代表客户端凭证错误、404代表端点地址错误、400代表请求参数缺失或格式错误。

修正后的Token获取实现

import base64
import requests

client_id = "abcd123"
client_secret = "EFGH456"

# 可根据API文档要求切换编码为ISO-8859-1
auth_content = f"{client_id}:{client_secret}".encode("utf-8")
authorization = base64.b64encode(auth_content).decode("ascii")

headers = {
    "Authorization": f"Basic {authorization}",
    "Content-Type": "application/x-www-form-urlencoded"
}
body = {
    "grant_type": "client_credentials"
}

# 替换为API文档给出的专属Token请求地址
token_endpoint = "https://mywebsite/api/oauth/token"
response = requests.post(token_endpoint, data=body, headers=headers)

# 调试用输出
print(f"响应状态码:{response.status_code}")
print(f"响应详情:{response.text}")

# 提取Bearer Token
if response.status_code == 200:
    token_info = response.json()
    # 提取token和有效期,不同服务商返回的key可能有差异,以实际返回为准
    access_token = token_info["access_token"]
    expire_seconds = token_info.get("expires_in", 3600)
    print(f"获取成功,Bearer Token为:{access_token}")

Token的存储与使用

  • 本地调试场景:可临时存储在变量中,调用业务接口时在请求头添加Authorization: Bearer {access_token}即可,无需再携带client_id和client_secret,示例如下:
biz_headers = {
    "Authorization": f"Bearer {access_token}"
}
# 调用业务接口
biz_resp = requests.get("https://mywebsite/api/你的业务接口路径", headers=biz_headers)
print(biz_resp.json())
  • 生产环境场景:需将Token和有效期一起存入缓存(如进程内缓存、Redis),到期前自动重新申请,禁止硬编码在代码或明文配置文件中,避免凭证泄露。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 22:24:03