Third party login of python website, social auth app Django module,
The social auth app Django module is a third-party login OAuth2 protocol module for Django
At present, the popular third-party login adopts OAuth2 protocol
Installation:
pip install social-auth-app-django
settings.py configuration:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #Third party login 'social_django', ]
The next step is to perform the migration:
python manage.py migrate
The beginning of social is the third-party table we generated!
Then we continue to configure settings.py:
Configure here. When a user logs in, if the user does not exist, the user will be automatically created in the user table and associated with the user information
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
#Third party login
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
#Notify in profile Django Use our custom authentication backend AUTHENTICATION_BACKENDS = [ 'users.utils.UsernameModelBackend',
'social_core.backends.weibo.WeiboOAuth2', #micro-blog 'django.contrib.auth.backends.ModelBackend', #Specify the modelbackend class of django]
Third party parameter configuration:
# User key SOCIAL_AUTH_WEIBO_KEY = ''
# User secret SOCIAL_AUTH_WEIBO_SECRET = ''
# Address of user jump after login SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://127.0.0.1:8080/index.html'
Configure the primary route:
urlpatterns = [ url('^xadmin/', xadmin.site.urls), # Third party login url('', include('social_django.urls')), ]
Let's also configure the callback URL:
In the advanced information of your own application, edit the authorization callback page http://127.0.0.1:8000/complete/weibo/. The yellow arrow can be left blank
Finally, log in to test whether there are users in your social auth table
Log in successfully and jump to the home page. It is found that it is not logged in. We need to modify the source code
We need to find actions.py in the social core directory in the environment
Then in about 100 lines, put the following line of code
return backend.strategy.redirect(url)
Revised to:
from rest_framework_jwt.serializers import jwt_encode_handler,jwt_payload_handler
response = backend.strategy.redirect(url) payload = jwt_payload_handler(user) response.set_cookie("name", user.username if user.username else user.username, max_age=24 * 3600) response.set_cookie("token", jwt_encode_handler(payload), max_age=24 * 3600) return response
After modification, users can be displayed after login!