Implementing Social Login in Django

Vinaykumarmaurya
Analytics Vidhya
Published in
5 min readNov 13, 2021

Using social-auth-app-django library

In this blog, I will guide you on how to implement social login in Django. Basically, I will cover google and Github authentication, you can do Twitter and Facebook authentication in the same way.

Make sure you already created your Django project. The next step is you need to install social-auth-app-django package.

Installation

We will install it through pip.

pip install social-auth-app-django

Configurations

Add social_django to your INSTALLED_APPS in your settings.py and then migrate your database.

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
'social_django',

]
python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, social_django Running migrations: Applying social_django.0001_initial... OK Applying social_django.0002_add_related_name... OK Applying social_django.0003_alter_email_max_length... OK Applying social_django.0004_auto_20160423_0400... OK Applying social_django.0005_auto_20160727_2333... OK Applying social_django.0006_partial... OK

Now we need to update MIDDLEWARE adding at the end SocialAuthExceptionMiddleware .

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', # <--
]

Now time to update the context_processors

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', # <--
],
},
},
]

The next step is to add the social auth backend.

AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2', # github <----
'social_core.backends.twitter.TwitterOAuth', # twitter <----
'social_core.backends.facebook.FacebookOAuth2', # facebook <----
'social_core.backends.google.GoogleOAuth2', # google <----
'django.contrib.auth.backends.ModelBackend',
)

Here I added backend for Github, Twitter, Facebook, Google but as I said I am gonna show you GitHub and google authentication. Now in your urls.py add social-auth-app-django url .

from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
path('admin/', admin.site.urls),
path('',include('polls.urls')),
path('oauth/', include('social_django.urls'namespace='social'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Add your view and template to handle the login.

# In views.pydef social_login(request):

return render(request,'social_login.html')
# Inside template {%extends 'base.html'%}
{%load static%}
{% load crispy_forms_tags %}
{%block home%}
<div class="container mt-4 bg-white p-3">
<a class="btn btn-primary" href="{% url 'social:begin' 'github' %}"><i class="fab fa-github"></i>&nbsp;Login</a>
<a class="btn btn-primary" href="{% url 'social:begin' 'google-oauth2' %}"> <i class="fab fa-google"></i>&nbsp;Login</a>
</div>
{%endblock%}

Now I’ll start with the GitHub Authentication.

GitHub Authentication

Log in to your GitHub account, go to Settings. In the left sidebar, there is Developer settings option. Click on OAuth applications and click New OAuth App . A Form will appear fill in the relevant info and submit it .

GitHub OAuth Form

Information in the above screenshot is just for testing purposes and it will work on the local server. After submitting the form you will get the Client ID and the Client Secrets. You need to copy both keys and paste them into your setting.py file.

SOCIAL_AUTH_GITHUB_KEY = '072fdd566d6e054wfe346f'
SOCIAL_AUTH_GITHUB_SECRET = 'e89072f86d42f3f44b4d9d67997b326bc0'

That's all we needed for the GitHub Login . Now try to log in with the GitHub.

GitHub Login Success

Google Authentication

For Google authentication again we need Google Client ID and Client Secrets. Go to Google Developer Console and click on New Project, I have created a project with the name Social Auth.

Now click on +CREATE CREDENTIALS and select OAuth client ID a form will open, fill in the relevant information. Before that, you need to configure the Consent Screen.

OAuth Client ID

Click on CONFIGURE CONSENT SCREEN button and once the configuration is done click on create credential below form will open on choosing web application as an option.

OAuth Client ID

Click on create button you will get your Client ID and the Client Secrets.

Client ID

That's all we wanted. Now copy the client ID and the Client Secret and paste them into your settings.py file.

SOCIAL_AUTH_GITHUB_KEY = '072fdd56598626f'
SOCIAL_AUTH_GITHUB_SECRET = 'e89072f86d42f3f4997b326bc0'
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '6390808614-qjduvv0eu1ehdf6pr1aqesc.apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'zY5rWkqetCWnnQ'

Now try to log in with Google. Select your google account you want to authentication that's all. Congratulations !!

Now the situation is I want to allow only certain google email authentication. Suppose in an organization all employees have the organization-based domain of google account and we want to authorize by the organization-based account, not the personal account for that we can do some tweaks.

Let say the organization's name is XYZ and employees email ends with @xyz.com . In your settings.py

# domain white list
SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['xyz.com']

That's all? The above piece of code will work fine but the user will not be able to know why authentication declined with the personal Gmail account. To convey some message we can add pipelines. Create a file piplines.py

from django.shortcuts import redirect
from django.contrib import messages
from django.contrib.auth.models import User


def auth_allowed(backend, details, response,request, *args, **kwargs):
if not backend.auth_allowed(response, details):
messages.error(request, 'Please Login with the Organization Account')
return redirect('login')

Add this pipeline to your settings.py file

# Social Auth pipeline
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'webapp.pipeline.auth_allowed', # <------
'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',

)

Now you can able to authenticate only a limited domain-based Gmail account.

Congratulation! you have successfully done Google and GitHub authentication in Django.

For more details, you can visit Django Social Auth Doc .

Follow me for more upcoming posts and thanks if my post helped you !!

--

--

Vinaykumarmaurya
Analytics Vidhya

Passionate Python Developer | Stepping towards Data Science