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

Python使用Authlib获取OLX Partner API V2 OAuth授权码遇阻求助

OLX API授权码获取问题排查

问题描述

我正在研究OLX API,尝试在Python中实现授权并获取token,但卡在获取Authorization Code的环节。我是编程新手,从未接触过这类授权方式。

我的代码片段:

client_id = 'xxxx'
client_secret = 'xxxx'
authorization_base_url = 'https://www.olx.ua/oauth/authorize'
token_url = 'https://www.olx.ua/api/open/oauth/token'
redirect_uri = 'http://www.example.com/'     # Should match Site URL
scope = 'v2 write read'
grant_type='authorization_code'
import hashlib
import requests
from authlib.integrations.requests_client import OAuth2Session
olx = OAuth2Session(client_id, client_secret, scope=scope,redirect_uri=redirect_uri)
authorization_uri, state = olx.create_authorization_url(authorization_base_url)
user_agent_val = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
   (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
payload={'username': 'example@gmail.com','password': hashlib.md5(b"xxxxx")}  
headers = {'User-Agent':user_agent_val}
response = requests.request("GET", authorization_uri, headers=headers, data=payload)
print(response.url) 

我期望response变量返回包含code和state的redirect_url,但实际得到的是authorization_uri。将authorization_uri输入浏览器完成授权后,能正常跳转到目标redirect_url/code&state,请问我哪里出错了?


问题原因与解决方法

核心逻辑错误

OAuth2的授权码模式(Authorization Code Flow)不允许第三方应用直接通过代码提交用户的账号密码,这个流程的设计初衷就是保护用户隐私:必须由用户手动在OLX官方的授权页面输入账号密码,完成授权后,OLX才会将授权码(code)通过重定向返回给你的应用。

你用requests直接请求授权地址并携带账号密码,OLX服务器会识别出这不是用户在浏览器的合法操作,因此不会返回带code的重定向地址,只会返回授权页面本身。

代码中的具体问题

  • 错误地通过requests携带payload(账号密码)请求授权地址,这不符合OAuth2授权码流程的规范
  • 没有利用authlib的完整流程,OAuth2Session主要用于后续用授权码换取token,而授权码的获取必须引导用户在浏览器中完成

修正后的实现步骤与代码

  1. 生成授权URL,引导用户在浏览器中打开并完成授权
  2. 获取授权后跳转的URL(包含code和state参数)
  3. 用授权码换取token
client_id = 'xxxx'
client_secret = 'xxxx'
authorization_base_url = 'https://www.olx.ua/oauth/authorize'
token_url = 'https://www.olx.ua/api/open/oauth/token'
redirect_uri = 'http://www.example.com/'     # 必须与OLX开发者后台设置的Site URL完全一致
scope = 'v2 write read'

from authlib.integrations.requests_client import OAuth2Session

# 1. 创建OAuth2会话并生成授权URL
olx = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)
authorization_uri, state = olx.create_authorization_url(authorization_base_url)

print("请在浏览器中打开以下链接完成授权:")
print(authorization_uri)

# 2. 用户授权后,复制浏览器地址栏的完整URL(包含code和state)输入到这里
redirect_response = input("请输入授权完成后的跳转URL:")

# 3. 用授权码获取访问token
token = olx.fetch_token(token_url, authorization_response=redirect_response, client_secret=client_secret)

print("成功获取到Token:")
print(token)

补充说明

授权码模式是OAuth2中最安全的授权方式,因为你的应用永远不会接触到用户的账号密码,只会拿到临时的授权码(code),再用code换取有效期有限的token。如果需要长期使用,可以后续用refresh token刷新获取新的access token。


内容的提问来源于stack exchange,提问作者Олег Волосюк

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:20:37