Django集成LinkedIn OAuth2遇权限不足:无法访问/userinfo接口
LinkedIn OAuth2集成403权限不足问题排查
问题背景
在Django应用中集成LinkedIn OAuth2社交登录,已按授权码流程完成配置:
- 授权请求中设置
scope=profile,且应用后台已配置该权限 - 成功获取
access_token,但调用https://api.linkedin.com/v2/userinfo或v2/me接口时返回403错误:{"serviceErrorCode":100,"message":"Not enough permissions to access: GET /userinfo","status":403}
代码片段
def login(request): return render(request, 'login.html') def authenticate(request): redirect_url = f'https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY}&redirect_uri={settings.LOGIN_REDIRECT_URL}&state={settings.STATE}&scope=profile' return redirect(redirect_url) def complete(request): code = request.GET.get('code', None) state = request.GET.get('state', None) url = "https://www.linkedin.com/oauth/v2/accessToken" headers = {"Content-Type": "application/x-www-form-urlencoded"} payload = { 'grant_type': 'authorization_code', 'code': code, 'client_id': settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY, 'client_secret': settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET, 'redirect_uri': settings.LOGIN_REDIRECT_URL } response = requests.post(url, headers=headers, data=payload) if response.status_code == 200: access_token = json.loads(response.content)['access_token'] print(access_token) info_url = 'https://api.linkedin.com/v2/userinfo' headers = {'Authorization': f'Bearer {access_token}'} info_response = requests.get(info_url, headers=headers) print(info_response.content) # 报错内容:b'{"serviceErrorCode":100,"message":"Not enough permissions to access: GET /userinfo","status":403}'
问题原因与解决方案
1. Scope参数需指定具体子权限
LinkedIn的profile是聚合权限,仅使用profile无法满足接口访问要求:
- 调用
v2/userinfo需要openid+profile组合权限 - 调用
v2/me需要r_liteprofile或r_fullprofile权限
修改授权请求的scope参数(多权限用空格分隔,URL中需转义为%20):
redirect_url = f'https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={settings.SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY}&redirect_uri={settings.LOGIN_REDIRECT_URL}&state={settings.STATE}&scope=openid%20profile'
2. Redirect URI的HTTPS要求
LinkedIn OAuth2强制要求生产环境的redirect URI必须为HTTPS;本地开发可使用http://localhost:端口作为例外,但上线前必须切换为HTTPS,否则会触发权限验证异常。
3. 应用权限配置验证
确认LinkedIn开发者后台的配置:
- 为应用添加「Sign In with LinkedIn」产品
- 在「Auth」页面的「Scopes」部分,勾选
openid、profile等所需权限,保存后需重新生成授权链接
4. 接口调用需添加协议版本头部
部分LinkedIn v2接口要求携带X-Restli-Protocol-Version头部,否则会返回权限或格式错误:
headers = { 'Authorization': f'Bearer {access_token}', 'X-Restli-Protocol-Version': '2.0.0' } info_response = requests.get(info_url, headers=headers)
内容的提问来源于stack exchange,提问作者RAHUL
相关产品推荐
相关产品推荐

