我开始使用 LinkedIN API,运行以下代码后,它会打开一个 linkedIn 窗口,其中显示:
“糟糕,出了点问题。 五秒钟后,您将被重定向到:127.0.0.1"
5 秒后,我到达 URL:
显示消息“错误:LinkedIn 未提供代码参数。请检查您的应用程序设置。”
请帮忙!
import requests
from flask import Flask, redirect, request
app = Flask(__name__)
# Define your LinkedIn application credentials
client_id = 'xxx'
client_secret = 'xxx'
redirect_uri = 'http://127.0.0.1:5000/callback'
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
state = '123456' # This should be a randomly generated value in production!
@app.route('/')
def login():
\# Step 1: Redirect the user to LinkedIn's OAuth 2.0 authorization page to get the authorization code.
params = {
'response_type': 'code',
'client_id': client_id,
'redirect_uri': redirect_uri,
'state': state,
'scope': 'r_emailaddress',
}
auth_url = requests.Request('GET', authorization_base_url, params=params).prepare().url
return redirect(auth_url)
@app.route('/callback')
def callback():
\# Step 2: Capture the code parameter LinkedIn sends to our callback URL
code = request.args.get('code')
returned_state = request.args.get('state')
# Check if the state matches to prevent CSRF attacks
if returned_state != state:
return "Error: State value did not match. Possible CSRF attack.", 400
if not code:
return "Error: No code parameter provided by LinkedIn. Check your application settings.", 400
# Step 3: Exchange the authorization code for an access token
token_data = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': redirect_uri,
'client_id': client_id,
'client_secret': client_secret
}
token_response = requests.post(token_url, data=token_data)
token_json = token_response.json()
if 'access_token' not in token_json:
return f"Error obtaining access token. {token_json.get('error_description')}", 400
access_token = token_json['access_token']
# At this point, you have the access token and can make authenticated LinkedIn API calls.
# Example: Fetching profile details (just for demonstration)
headers = {'Authorization': f'Bearer {access_token}'}
profile_response = requests.get('https://api.linkedin.com/v2/me', headers=headers)
return profile_response.json()
if __name__ == '__main__':
app.run(debug=True)
我尝试了不同的范围,例如“r_emailaddress”和“r_basicprofile”。我还可以访问图像中的以下产品:
我已经审查了同样的问题,但没有任何效果,因为平台在 5 年内发生了很大变化: LinkedIn oAuth2 身份验证中的 unauthorized_scope_error