PAYATHON 2026

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 判断回调参数容易误判。

解决步骤

  1. 先确认请求的是 OAuth2 authorization endpoint,且 redirect_uri 与 OAuth2 后台注册值完全一致(scheme、host、port、path 均一致)。
  2. 用 allow_redirects=False 发起第一次请求,读取 response.status 和 response.headers['Location'],从 Location 的 query 中取 code 和 state。
  3. 如果确实需要自动跟随,检查 response.history 和最终 response.url,遍历所有 URL 的 query,找到包含 code 的那一跳。
  4. 如果返回 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();这一点不影响重定向问题本身。

备注:内容仅供参考。