These days, rather than login with ID + PW, we often prefer to login via openID authentication. These OAUTH are provided by various social networks, such as Twitter, Google, Facebook etc.
To allow users login with OAUTH, there is a Django package recommended,
social-auth-app-django
.
For more details of its documentations, here is the
link.

:
OAuth 2.0: An Overview(YouTube)
1.
[Installation + Settings]
Install
social-auth-app-django
$pipenv install social_auth_app_django
Add path or url in
url.py
:
path('', include('social_django.urls', namespace='social')),
Install app under
settings.py
:
INSTALLED_APPS = (
...
'social_django',
...
)
MIDDLEWARE = [
...
'social_django.middleware.SocialAuthExceptionMiddleware',
]
AUTHENTICATION_BACKENDS = (
#Insert these before django's backend
'social_core.backends.open_id.OpenIdAuth',
'social_core.backends.google.GoogleOpenId',
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.google.GoogleOAuth',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.yahoo.YahooOpenId',
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
#Add pipelines
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.auth_allowed',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates').replace('\\', '/')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
...
#Add these
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
2.
[Get access token]
To use OAUTH from social networks, you need to register and create an app with their services.
In this demo, we are using
Twitter:

p.s. "Request email address" should be checked,as we need to grab visitors' email address to merge any existing account on our site.
Copy the
KEY
and
SECRET
from Twitter application settings and paste to
settings.py
:
SOCIAL_AUTH_TWITTER_KEY = 'YOUR TWITTER APP KEY'
SOCIAL_AUTH_TWITTER_SECRET = 'YOUR TWITTER APP SECRET'
p.s. If you are using facebook OAUTH,you may also need this pipeline to grab email address:
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {'fields': 'id,name,email'}
For security reason, you should always keep the
KEY and
SECRET under
.env
using
python-decouple
.
3.
[font-end settings]
Finally, we add a link into
login.html
:
<a href='{% url "social:begin" "twitter" %}'>Login with Twitter</a>
Now, you should be able to see this page of authenication using the link.