我们正在尝试基于https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context
实现LinkedIn API身份验证模块。
我们将应用程序设置的重定向URL作为公司的主页(https://www.{site}.com
),并且能够从重定向URL获取身份验证代码。但是,在交换访问令牌时,它在下面给我们401错误:
b'{"error":"invalid_request","error_description":"Unable to retrieve
access token: authorization code not found"}'
奇怪的是,它可以正常工作,并且如果我们将重定向URL切换到API控制台中的https://www.example.com
之类的其他站点,我们就能交换访问令牌的代码。下面是我们使用的Py3代码:
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import linkedin_compliance_fix
# Credentials and redirect uri you get from registering a new application
client_id = 'client_id'
client_secret = 'client_secret'
redirect_url = 'redirect_url'
# OAuth endpoints given in the LinkedIn API documentation (check for updates)
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
# Authorized Redirect URL (from LinkedIn config)
o2_session = OAuth2Session(client_id=client_id, redirect_uri=redirect_url, scope=['rw_ads', 'r_ads_reporting'])
linkedin = linkedin_compliance_fix(o2_session)
# 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:')
linkedin.fetch_token(token_url, include_client_id=client_id, client_secret=client_secret, authorization_response=redirect_response)
token = linkedin.access_token
了解到auth代码的寿命很短,因此在将代码发布回URL后的第二秒都尝试了重定向URL。谁能想到任何原因导致不同的重定向URL出现这种奇怪的不同行为。