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

如何用Python实现OAuth2请求获取Access Token?(遇403错误)

解决OAuth2获取Token时的403错误

你的代码存在几个关键问题,直接导致了403错误,下面逐一说明并给出修正方案:

问题分析

  • 参数位置错误:你把grant_type、code、redirect_uri这些表单参数都塞进了请求头里,按照OAuth2规范,这些参数应该放在POST请求的请求体中,而非headers。
  • 缺少Basic认证头:API要求必须携带Authorization: Basic {{basicAuthentication}}头,但你的代码完全没处理这部分——需要先对client_id和client_secret做URL编码,用冒号拼接后做Base64编码,再加上Basic 前缀。
  • 语法错误:headers字典里的"grant_type=authorization_code"后面没加逗号,且Python注释要用#而非//,这会直接导致代码运行报错。

修正后的代码

import requests
import base64
from urllib.parse import quote_plus

# 配置参数
client_id = "23232323"
client_secret = "12344555"
code = "1223455"
redirect_uri = "http://localhost:8080/callback"
url = "https://identityservice.nmbrs.com/connect/token"

# 1. 生成Basic Authentication头
# 先对client_id和client_secret做URL编码(遵循RFC6749)
encoded_client_id = quote_plus(client_id)
encoded_client_secret = quote_plus(client_secret)
# 拼接成"client_id:client_secret"格式后Base64编码
basic_auth_str = f"{encoded_client_id}:{encoded_client_secret}"
basic_auth_bytes = basic_auth_str.encode('utf-8')
basic_auth_base64 = base64.b64encode(basic_auth_bytes).decode('utf-8')
# 构造请求头
headers = {
    'Content-Type': "application/x-www-form-urlencoded",
    'Authorization': f"Basic {basic_auth_base64}"
}

# 2. 构造请求体参数
data = {
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': redirect_uri
}

# 3. 发送POST请求
response = requests.post(url, headers=headers, data=data)
# 打印响应结果
print(response.status_code)
print(response.json())

关键步骤说明

  • URL编码:用quote_plus处理client_id和client_secret,避免特殊字符引发的编码异常。
  • Base64编码:将拼接后的字符串转为字节流再编码,最后转回字符串用于请求头。
  • 请求体传递:用data参数传递表单数据,requests会自动处理application/x-www-form-urlencoded格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:55:20