User account validation with social-auth-django

Martín Lamas
Trabe
Published in
2 min readSep 3, 2018
Photo by Tony Webster on Unsplash

During the development of one of my django projects I needed to restrict which users could use the application. Specifically, only users with a specific domain in their email address can be registered. To achieve this I had to modify the social-auth-django pipeline to customize the authentication process of my application.

Introduction to the social-auth-django pipeline

The social-auth-django library uses a pipeline that manages the user authentication (registry, login and logout). Each step of the pipeline generates a result that can be used in the next, and so on. The default pipeline for the authentication process is shown here (including the original source comments):

This pipeline can be customized by adding, deleting or modifying steps to provide a different authentication behaviour.

Customizing the user account creation

In this example we will customize the user account creation to add the email address domain whitelist. To do this, we will create a python module:

The function create_user first checks if the user is already registered inspecting the user parameter. This parameter contains the user instance when the user is already registered (the instance is injected and forwarded by the previous step in the pipeline). If the user is registered no action is required. If the user does not exists yet then the details parameter is inspected to retrieve the user email address that is being used to do the authentication. This email address is matched against the whitelist using the allowed_email function. When the validation is successful, the user is created using the strategy instance parameter. There’s no magic here :)

Setting the pipeline

The pipeline configuration is built using an ordered list with the different steps. This configuration must be placed in the project settings file as shown here:

In this example, we replace the social_core.pipeline.user.create_user step in the default pipeline shown earlier with our custom version. When a user tries to authenticate in the application, all of the steps of this custom pipeline will be executed. If the user authenticates for the first time, then the validation is performed. That’s all.

Conclusions

With social-auth-django we can add in our application support for an authentication/registration mechanism which supports several auth providers and protocols like OAuth (version 1 and 2) or OpenId . In some scenarios we could need to customize the authentication process to meet the application requirements. The library provides a mechanism that allows us to modify the pipeline and change the user authentication flow.

--

--