使用Python Social Auth来集成第三方登录(QQ、微信、微博)
    官方文档:https://python-social-auth.readthedocs.io/en/latest/
    DRF使用social文档:
    使用Python Social Auth来集成第三方登录(QQ、微信、微博) - 图1
    1、首先安装依赖包:

    1. pip install social-auth-app-django
    2. 1

    2、在INSTALLED_APPS中加入social_django

    1. INSTALLED_APPS = (
    2. ...
    3. 'social_django',
    4. ...
    5. )
    6. 12345

    3、(mysql)数据库迁移(无需执行makemigration,源码中makemigration文件已经生成好):

    1. python manage.py migrate
    2. 1

    注意:mysql的storage_engine需要时INNODB

    4、在setting文件中添加AUTHENTICATION_BACKENDS:

    1. AUTHENTICATION_BACKENDS = (
    2. 'social_core.backends.weibo.WeiboOAuth2',
    3. 'social_core.backends.qq.QQOAuth2',
    4. 'social_core.backends.weixin.WeixinOAuth2',
    5. ...
    6. 'django.contrib.auth.backends.ModelBackend',
    7. )
    8. 1234567

    5、配置url

    1. urlpatterns = patterns('',
    2. ...
    3. url('', include('social_django.urls', namespace='social'))
    4. ...
    5. )
    6. 12345

    6、在setting文件里的TEMPLATES里添加’social_django.context_processors.backends’和’social_django.context_processors.login_redirect’,如下:

    1. TEMPLATES = [
    2. {
    3. ...
    4. 'OPTIONS': {
    5. ...
    6. 'context_processors': [
    7. ...
    8. 'social_django.context_processors.backends',
    9. 'social_django.context_processors.login_redirect',
    10. ...
    11. ]
    12. }
    13. }
    14. ]
    15. 1234567891011121314

    7、在setting文件里配置app_key和app_secret:

    1. SOCIAL_AUTH_WEIBO_KEY = 'xxxxxxxxxxxxxxxxxx'
    2. SOCIAL_AUTH_WEIBO_SECRET = 'xxxxxxxxxxxxxxxxxx'
    3. SOCIAL_AUTH_QQ_KEY = 'xxxxxxxxxxxxxxxxxx'
    4. SOCIAL_AUTH_QQ_SECRET = 'xxxxxxxxxxxxxxxxxx'
    5. SOCIAL_AUTH_WEIXIN_KEY = 'xxxxxxxxxxxxxxxxxx'
    6. SOCIAL_AUTH_WEIXIN_SECRET = 'xxxxxxxxxxxxxxxxxx'
    7. 12345678

    8、在setting中配置指明登录成功后跳转的页面:

    1. SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/index/'
    2. 1

    以上配置好之后就可以分别使用微博、QQ、微信第三方登录了:
    微博:http://127.0.0.1:8000/login/weibo/
    QQ:http://127.0.0.1:8000/login/qq/
    微信:http://127.0.0.1:8000/login/weixin/
    注意:要按照微博等第三方开放平台的要求设置好授权的回调页
    例如微博要创建好应用,设置好授权回调页:http://127.0.0.1:8000/complete/weibo/
    QQ和微信也是如此
    使用Python Social Auth来集成第三方登录(QQ、微信、微博) - 图2

    登录逻辑:
    如果是第一次登录,那么就会在social_auth_usersocialauth表中新建一条记录,也会在user表中创建一条记录,并自动设置好username(去微博的个人信息中拿到,如果不存在,则自动生成一串唯一ID),然后通过外键user_id关联,,如果不是第一次登录,那么就会在此表中查询user_id
    使用Python Social Auth来集成第三方登录(QQ、微信、微博) - 图3
    使用Python Social Auth来集成第三方登录(QQ、微信、微博) - 图4

    注意:登录成功后像前段返回的默认是session_id,如果用的JWT登录则需要返回token,那么此时就需要修改源码。
    使用Python Social Auth来集成第三方登录(QQ、微信、微博) - 图5
    首先把social_core复制出来,放到django项目的第三方包里
    找到actions.py文件(social_core–actions.py),再找到do_complete函数
    修改函数末尾返回的代码:

    1. response = backend.strategy.redirect(url)
    2. payload = jwt_payload_handler(user)
    3. response.set_cookie("name", user.name if user.name else user.username, max_age=24*3600)
    4. response.set_cookie("token", jwt_encode_handler(payload), max_age=24*3600)
    5. return response