DRF第三方登錄,我們將使用第三方包實現!!!
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引擎要使用innerdb。
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
原文:https://blog.csdn.net/qq_34374753/article/details/84501264