Django Rest Framework第三方登录

第三方登录已有大神为我们封装好了包,我们一起来学习怎么使用吧

  • 1、首先安装
pip install social-auth-app-django

文档请看 https://python-social-auth.readthedocs.io/en/latest/configuration/django.html

  • 2、在setting文件中
    INSTALL_APP中加入
		'social_django',
  • 3、生成数据表
    由于第三方登录包已经生成好了migration的文件,所以我们只需migrate就好
    出现warning不需要在意。记得mysql要使用innodb。
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "",
        'USER': '',
        'PASSWORD': "",
        'HOST': "127.0.0.1",
        #第三方登录。。。。不设置migration会出错
        'OPTIONS': {'init_command': 'SET default_storage_engine=INNODB;'}
    }
}

执行migrate之后,数据库会生成新的表用来记录第三方登录

  • 4、setting文件中
    设置邮箱和用户名和手机号均可登录
# 设置邮箱和用户名和手机号均可登录
AUTHENTICATION_BACKENDS = (
    'users.views.CustomBackend',
    #第三方登录配置之微博登录
    'social_core.backends.weibo.WeiboOAuth2',
    #第三方登录配置之QQ登录
    'social_core.backends.qq.QQOAuth2',
    #第三方登录配置之微信登录,微信有两种:oauth2 和 oauth2app,我们使用auth2
    'social_core.backends.weixin.WeixinOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                #加入
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

设置第三方登录的应用的key与secret
需要自己去第三方平台创建应用,获取应用的key与secret

# 第三方登录相关

#微博应用的key与secret
SOCIAL_AUTH_WEIBO_KEY = ''
SOCIAL_AUTH_WEIBO_SECRET = ''

#QQ应用的key与secret
SOCIAL_AUTH_QQ_KEY = ''
SOCIAL_AUTH_QQ_SECRET = ''

#微信应用的key与secret
SOCIAL_AUTH_WEIXIN_KEY = ''
SOCIAL_AUTH_WEIXIN_SECRET = ''

#配置用户授权之后重定向跳转的url
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/index/'

  • 5、url的配置
    # 首页
    path('index/', TemplateView.as_view(template_name='index.html'), name='index'),
    # 第三方登录
    path('', include('social_django.urls', namespace='social'))

一点小问题

  • 配置完成之后可以进行登录,但首页不会显示用户名
    drf登录获取的是cookie,所以需要更改social_core的源码使得它可以setcookie
    social_core/actions.py:
from rest_framework_jwt.serializers import jwt_encode_handler,jwt_payload_handler

def do_complete(backend, login, user=None, redirect_name='next',
                *args, **kwargs):
	......
	    if backend.setting('SANITIZE_REDIRECTS', True):
        allowed_hosts = backend.setting('ALLOWED_REDIRECT_HOSTS', []) + \
                        [backend.strategy.request_host()]
        url = sanitize_redirect(allowed_hosts, url) or \
              backend.setting('LOGIN_REDIRECT_URL')
              
    # 修改源码适配drf
    response = backend.strategy.redirect(url)
    payload = jwt_payload_handler(user)
    response.set_cookie("name", user.name if user.name else user.username, max_age=24 * 3600)
    response.set_cookie("token", jwt_encode_handler(payload), max_age=24 * 3600)
    return response

猜你喜欢

转载自blog.csdn.net/qq_34374753/article/details/84501264