我正在尝试运行requests-OAuth2 LinkedIn示例。我已经能够解决示例过时的一些问题,但似乎无法使最后一行正确运行。
运行程序的响应对象内容:
b'{“ serviceErrorCode”:100,“消息”:“参数中存在不允许的字段:处理字段[/ access_token]时出现数据处理异常”,“状态”:403}
r_liteprofile
。我添加了注释,以说明我对request-oauthlib网站上的股票教程进行了哪些更改。
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import linkedin_compliance_fix
# Credentials you get from registering a new application
client_id = vault.CLIENT_ID
client_secret = vault.CLIENT_SECRET
# CHANGE: Scope is necessary to avoid permission errors
scope = ['r_liteprofile', 'r_emailaddress', 'w_member_social']
redirect_url = 'http://127.0.0.1'
# OAuth endpoints given in the LinkedIn API documentation (you can check for the latest updates)
# CHANGE: updated urls
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
# Authorized Redirect URL (from LinkedIn configuration)
# CHANGE: added scope argument to OAuth2Session init method
linkedin = OAuth2Session(client_id, redirect_uri=redirect_url, scope=scope)
linkedin = linkedin_compliance_fix(linkedin)
# Redirect user to LinkedIn for authorization
authorization_url, state = linkedin.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here:')
# Fetch the access token
# CHANGED: LinkedIn required client_id to be in body, flipped include_client_id to True
linkedin.fetch_token(token_url,client_secret=client_secret,
include_client_id=True,authorization_response=redirect_response)
# CHANGED: Just an example of a header I tried passing to the get method below
headers = {'X-Restli-Protocol-Version': '2.0.0'}
r = linkedin.get('https://api.linkedin.com/v2/me')
print(r.content)
答案 0 :(得分:1)
最终,我传递的请求网址包含一个不允许的字段。手动查看url显示了两个字段:
access_token
requests-oauthlib/requests_oauthlib/oauth2_session.py
查看OAuth2-Requests源代码,将第二个字段添加到URL,然后再发出最终请求。
oauth2_session.py
我想象有一个机制可以阻止这种行为,但是我找不到它,我对他们的github和其他地方的评论/问题都没有得到答复。我的解决方案是使用request()
方法中的这个肮脏的修复程序在项目中复制old_version_url = url
url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers)
# Dirty work around to prevent the `access_token` parameter from being added
# to the url, causing a unpermitted parameters error requesting linkedin resource.
if "&access_token=" in url:
url = old_version_url
模块的修改版本。
shinydashboard
整个修改后的模块可以在此github存储库linkedin_assist/linkedin_assist/quick_fixes/oauth2_session.py
中找到