从 API 重定向 URL 捕获访问令牌

问题描述 投票:0回答:1

我正在尝试捕获 API 在身份验证过程中返回的访问令牌。从 API 进行身份验证过程的官方方法是:

from xyz_api import accessToken
app_id = "your_app_id"
app_secret = "your_app_secret"
app_session = accessToken.SessionModel(app_id, app_secret)
response = app_session.auth()

上面将返回一个 json,例如:

{

"code" : 200,

"data" : {

"authorization_code": "some random code"

},
}

现在,使用以下代码来生成 URL:

authorization_code = “your_authorization_code”

app_session.set_token(authorization_code)

url = app_session.generate_token()

现在这就是我开始遇到问题的地方。

现阶段,API作者推荐的是:

1. Use the generated URL and copy paste it into a browser. 
2. The browser will then do the authentication and return the access token to a redirect 
url (I used http://localhost:5000).
3. Copy and paste the access token from redirect URL

我想要的:

To be able to finish the authentication and get the access_token from
python code itself.

我尝试过的: 使用requests.get(url),但是不起作用。

有没有办法只使用 python 来完成这一切,而不需要打开浏览器

PS: The API I am trying to use is: https://api-docs.fyers.in/v1#authorization

进一步调查

经过进一步调查,我发现了以下内容:

  1. API使用oauth

  2. API作者提供的以下代码获取的URL

    url = app_session.generate_token()

与我编写以下代码时相同:

oauth = OAuth2Session('app_id')
authorization_url, state = oauth.authorization_url(url)
  1. 两种情况返回的 url 格式如下:

    https://api.fyers.in/api/v1/genrateToken?authorization_code=some_auth_code&appId=my_app_id

  2. 如果我在浏览器中复制粘贴此 URL,它会将 access_token 发送回我的redirect_url (http://localhost:5000)

  3. 我尝试使用 oauth::fetch_token 和以下代码获取访问令牌,但失败了:

    oauth1 = OAuth2Session('app_id',state = state,redirect_uri =“http:// localhost:5000”)

    token = oauth1.fetch_token('https://api.fyers.in/api/v1/genrateToken/', client_secret='app_secret', 代码='the_auth_code_returned')

非常感谢您的帮助。

python python-3.x python-requests oauth
1个回答
0
投票

您仅使用 Python 访问... 您不需要在浏览器中手动执行任何操作..

此 API 不确定您是否想要什么。

我相信你注册了一个APP,得到了你的

app_secret
步骤

response = app_session.auth()

authorization_code

来回答你
"data" : {

"authorization_code": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqaGdqZzg3NiQ3ODVidjVANjQ3NTZ2NSZnNyM2OTg3Njc5OHhkIjoiWElHVFVYVjBSSSIsImV4cCI6MTU2MTU5NzM5Ny41NjQxNTV9.Agl-Uus63NforrUEdbG7YUlPcbFXu9hLYm4akGuIBkU"

您可以像这样访问该授权令牌

import json 
r = json.dumps(reponse)
authorization_token = r['data']['authorization_code']

授权令牌和您

app_id
必须作为查询字符串传递到
https://api.fyers.in/api/v1/genrateToken?

然后,真实用户将被要求接受通过您的应用程序登录 如果接受,用户将被重定向到 URL *我想您在应用程序注册中通知。

让我知道是否有意义

© www.soinside.com 2019 - 2024. All rights reserved.