You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

登录成功后如何获取Authorization Code——LinkedIn OAuth(Django、Python)

解决LinkedIn登录后自动获取Access Token填充表单的问题

你完全没走错方向!只是可能没意识到social-auth-app-django已经帮你把Authorization Code到Access Token的转换全自动化了——根本不需要用户手动复制Code,整个流程都是后台悄悄完成的。我来给你拆解清楚怎么操作:

1. 先搞懂social-auth帮你做了什么

当用户点击LinkedIn登录按钮后:

  • 用户被跳转到LinkedIn的授权页面,同意授权你的应用
  • LinkedIn会自动把Authorization Code发送到你配置的回调URL(就是你在LinkedIn开发者后台填的那个,要和Django里SOCIAL_AUTH_REDIRECT_URI一致)
  • social-auth-app-django会立即用这个Code向LinkedIn请求Access Token,成功后把Token存在数据库的SocialToken表中,和当前用户绑定

2. 如何获取用户的Access Token

用户登录后,你可以直接从用户的社交认证记录里取出Token:

# 在你的视图函数里
from django.contrib.auth.decorators import login_required

@login_required
def fill_profile(request):
    # 获取当前用户的LinkedIn社交认证记录
    try:
        linkedin_auth = request.user.social_auth.get(provider='linkedin-oauth2')
        access_token = linkedin_auth.access_token  # 这就是你要的令牌!
    except request.user.social_auth.model.DoesNotExist:
        # 处理用户没通过LinkedIn登录的情况,比如跳转回登录页
        return redirect('social:begin', backend='linkedin-oauth2')
    
    # 接下来用Token拉取用户资料
    # ...

3. 用Access Token拉取LinkedIn资料填充表单

拿到Token后,调用LinkedIn的API获取用户信息,再把数据填充到表单里。举个简单的例子:

import requests

# 接上面的代码
headers = {
    'Authorization': f'Bearer {access_token}',
    'X-Restli-Protocol-Version': '2.0.0'  # LinkedIn API要求的头部
}
# 拉取基本资料和邮箱,字段可以根据你的表单需求调整
api_url = 'https://api.linkedin.com/v2/me?fields=id,firstName,lastName&projection=(elements*(handle~))'
email_url = 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))'

# 请求资料
profile_response = requests.get(api_url, headers=headers)
email_response = requests.get(email_url, headers=headers)

if profile_response.status_code == 200 and email_response.status_code == 200:
    profile_data = profile_response.json()
    email_data = email_response.json()
    
    # 解析数据(注意LinkedIn的返回格式是多语言的,这里取英文为例)
    first_name = profile_data['firstName']['localized']['en_US']
    last_name = profile_data['lastName']['localized']['en_US']
    email = email_data['elements'][0]['handle~']['emailAddress']
    
    # 填充表单,比如用ModelForm的initial参数
    from .forms import ProfileForm
    form = ProfileForm(initial={
        'first_name': first_name,
        'last_name': last_name,
        'email': email
    })
    
    return render(request, 'fill_profile.html', {'form': form})
else:
    # 处理API请求失败的情况
    return render(request, 'error.html', {'message': '无法获取LinkedIn资料'})

4. 你之前看到的“手动复制Code”是什么情况?

那些资料里的手动流程,一般是没有使用第三方OAuth库时的调试方式,或者是用来测试API的临时操作。但social-auth-app-django已经把整个OAuth2的授权流程封装得非常完善了,普通用户访问时完全不需要手动介入任何步骤。

最后要注意的细节

  • 确保你在LinkedIn开发者后台申请了对应的API权限:比如r_liteprofile(拉取基本资料)和r_emailaddress(拉取邮箱),不然API请求会返回权限错误
  • 检查回调URL是否完全匹配:LinkedIn后台的回调URL要和Django的SOCIAL_AUTH_REDIRECT_URI一模一样,包括http/https、端口号等
  • 如果Token过期了,social-auth-app-django会自动帮你刷新Token(只要你配置了刷新Token的权限),不需要你手动处理

内容的提问来源于stack exchange,提问作者Paru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:30:24