我研究 API OLX https://developer.olx.ua/api/doc。我正在尝试在 Python 中实现授权并获取令牌。卡在接收授权码的那一刻。我是初学者,我从未使用过此类授权。
这是我的代码
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': '[email protected]','password': hashlib.md5(b"xxxxx")}
headers = {'User-Agent':user_agent_val}
response = requests.request("GET", authorization_uri, headers=headers, data=payload)
print(response.url)
我希望在变量响应中收到redirect_url/code&state的字符串,但我得到字符串authorization_uri 如果我在授权后在浏览器中输入authorization_uri行,我将被重定向到所需的redirect_url/code&state 我做错了什么?
这里有两件事。您首先需要使用预期参数构建授权网址,例如
redirect_uri
、grant_type
、client_id
、client_secret
和 state
。 state
这里是一些随机字符串,它是您所在州的标识符。一些身份验证提供商需要 PKCE
字符串。
例如。 Auth Url 可以是
https://www.olx.ua/oauth/authorize/?client_id=123&response_type=code&state=x93ld3v&scope=read+write+v2&redirect_uri=http://myadomain.com/auth/connect
(注意:这将是一个 get 调用,您必须重定向到此 url)
你的参数在哪里:
{
"client_id": 123,
"response_type": code,
"state": x93ld3v,
"scope": "read write v2",
"redirect_uri': "http://myadomain.com/auth/connect"
}
您还需要在后端服务器或 UI 中添加逻辑(以重定向_uri 中的服务器为准)来处理
olx
服务器发布的参数,以进一步调用身份验证令牌。
服务器验证后,它将重定向到带有
redirect_uri
和 code
的 state
。您可以将此状态与您的状态相匹配,以确保这是正确的代码。 Code
是您当前会话的授权人,下一步将需要该授权人。
然后,您可以再次使用此代码通过
POST
api 进行 olx
调用以检索身份验证令牌(端点:/api/open/oauth/token
)。
{
"grant_type": "authorization_code",
"client_id": "",
"client_secret": "",
"code": "",
"scope": "v2 read write",
"redirect_uri": "http://myadomain.com/auth/connect"
}
您必须收到一个访问令牌和一个刷新令牌,您可以根据需要使用它们。
您可以参考olx.ua Auth文档了解更多详情。
authorization_uri, state = olx.create_authorization_url(authorization_base_url)
在authorization_uri中,我得到字符串
https://www.olx.ua/oauth/authorize?response_type=code&client_id=12345&redirect_uri=http%3A%2F%2Fwww.example.com%2Fru%2F&scope=v2+write+read&state=6yDKvzjFfN0uXrGJMUUUgjz3pzNilB
我发送的
response = requests.request("GET", authorization_uri, headers=headers, data=payload)
如何正确发送带有代码的重定向URL请求
要接收授权码,您需要通过文档中指定的url进行授权
成功登录后,您将被重定向到重定向网址(您为应用程序设置的),网址中带有参数
?code=
。
然后就可以使用code来获取Access token了。
另外,检查我用 python 编写的 API 包装器,这使得处理 OLX API 变得更加容易 https://github.com/Pawikoski/olx-api-wrapper