OAuth Authentication in Django with social-auth

During the development of my last django project I had to provide user authentication with Google accounts. To achieve this, I used the social-app-django library that implements an authentication/registration mechanism which supports several auth providers and protocols like OAuth (version 1 and 2) or OpenId.

A quick recap about OAuth

To provide user authentication Google supports several protocols including OAuth 2. OAuth is an open protocol that provides secure authorization for web, mobile and desktop applications in a simple and standard way. The protocol relies on a trusted third party to establish the authentication process. It grants client access to a resource delegating the authorization process to an external authorization server with the approval of the resource owner.

In this diagram you can see how it works:

A complete guide about how to use this protocol to access Google APIs is available here.

In this post, we’ll build a simple blog application using the OAuth protocol to provide user authentication with Google accounts.

Let’s go!

1. Installing the library

As a first step, we must install and enable the social-auth-app-django library in our django project. We can install this library using either pip or pipenv according to our environment/personal preferences.

If we choose pip:

pip install social-auth-app-django

or if we use pipenv:

pipenv install social-auth-app-django

Once the library has been installed, we must add the app to the INSTALLED_APPS list in the project settings file using the social_django identifier:

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

2. Adding the Google OAuth2 authentication backend

Back to Top