aiohttp OAuth2 重定向后 response.url 未变为 redirect_uri 如何获取 code
数据小陈
结论
response.url 在 aiohttp 里表示跟随重定向后的最终响应地址。它既不是调用时传入的 URL,也不一定等于 OAuth2 回调的 redirect_uri。你看到它变成 https://api.web/onboarding,说明整条重定向链最后停在 onboarding 页面,并没有回到携带 code 的 redirect_uri。因此,要取 code 不能只盯着最终的 response.url:要么关闭自动重定向,直接检查 Location;要么查看 response.history,在中间某次跳转里找。标准 OAuth2 授权码流程更建议让浏览器或 WebView 完成授权,再由回调服务接收并处理 code。
原因
session.get(..., allow_redirects=True) 默认会自动跟随 3xx 重定向。跟随过程中可能经过登录页、引导页或多次跳转,最终 response.url 只保留最后地址。若 OAuth2 服务器没有直接把客户端 302 到 redirect_uri,或者 redirect_uri 未注册、不匹配、缺少登录会话、state 校验失败等,就可能落到登录/onboarding 页。授权端点通常返回 302/303,而不是先返回 200 再重定向;所以用 response.status == 200 判断回调参数容易误判。
解决步骤
- 先确认请求的是 OAuth2 authorization endpoint,且
redirect_uri与 OAuth2 后台注册值完全一致(scheme、host、port、path 均一致)。 - 用
allow_redirects=False发起第一次请求,读取response.status和response.headers['Location'],从Location的 query 中取code和state。 - 如果确实需要自动跟随,检查
response.history和最终response.url,遍历所有 URL 的 query,找到包含code的那一跳。 - 如果返回 200 且页面是登录/onboarding,说明服务器没有按 OAuth2 回调重定向,通常是会话、注册参数或授权流程不对,不应继续从最终 URL 里硬取
code。
代码示例:
import aiohttp
from yarl import URL
async def get_oauth_code(session, auth_endpoint, client_id, redirect_uri):
params = {
'response_type': 'code',
'client_id': client_id,
'redirect_uri': redirect_uri,
}
async with session.get(auth_endpoint, params=params, allow_redirects=False) as resp:
print('status:', resp.status)
print('url:', resp.url)
print('location:', resp.headers.get('Location'))
if resp.status in (301, 302, 303, 307, 308):
location = resp.headers.get('Location')
if not location:
raise RuntimeError('重定向响应缺少 Location')
target = resp.url.join(URL(location))
code = target.query.get('code')
state = target.query.get('state')
return code, state, target
body = await resp.text()
raise RuntimeError(
f'未得到 OAuth2 重定向,status={resp.status}, body={body[:200]}'
)
如果已经自动跟随,可这样排查:
async with session.get(auth_endpoint, params=params) as resp:
urls = [h.url for h in resp.history] + [resp.url]
for u in urls:
print(u, 'code=', u.query.get('code'), 'state=', u.query.get('state'))
注意事项
response.url.query.get('code')只在最终 URL 确实带code时有效;最终 URL 已经丢了 query,就别再依赖它。- OAuth2 的
state要生成并校验,不能省。 - 若授权端点需要用户登录、MFA 或同意授权,后端直接 GET 通常拿不到
code,应改用浏览器/WebView 回调流程。 - 错误日志里
response.json是方法而非属性,读 JSON 用await response.json(),读文本用await response.text();这一点不影响重定向问题本身。
备注:内容仅供参考。
