Django Tools: Authentication with django-allauth module

Filed Under: Django
Allauth Python Min

Today, we’ll be working with the django-allauth module, a package that allows for third-party authentication in Django.

During the process of working with Django, we come to a conclusion that the reason behind the popularity of Django is similar to that of Python.

Why? Because it provides us with great functionality with a few simple packages. Well, do I have news for you!

Django can provide us with even more functionality through the use of registration applications that are provided by the community.

One of the best Django user registration package is the django-allauth registration app.

However, before we go ahead and work with the addition of external applications.

It’s probably for the best to refresh your mind on the basic concepts, with some of Django’s features,

If you’re done with the basics, let’s get into what the django-allauth tool is all about.

What is the django-allauth module?

The django-allauth module is one that provides our Django project with additional functionality.

It is a tool that can provide us with third-party authentication options ranging from Google Accounts to GitHub to Instagram logins.

Overall, providing an option for users to connect their accounts to our Django application.

This provides us with information which the user has already provided in their connected account.

Why do we need this module?

Synchronization is a great feature to allow the user to log in quickly and efficiently.

It also provides them the feature to change their details in one place and we can immediately see it take effect in another.

However, keeping that aside for now, let’s get started on working with django-allauth.

1. Installation of the django-allauth module

In order to work with django-allauth module, we do have a few prerequisites to install before getting started.

You can install the above libraries using the pip package manager for Python.

2. Setting up a Django project

Starting out with the Django project, we’ll need to,

  • Create a Django Project.
  • Install django-allauth.
pip install django-allauth
  • Modify the settings.py

We’ll need to make changes to the settings.py in the main Django root folder for the project.

Following are the sections where we’ll be changing the details to include the functionality of django-allauth.

3. Configuring the installed apps

Firstly, let’s add the components of the django-allauth module to the INSTALLED_APPS in the settings.py.

This connects the allauth application to our project, and note that we’re only adding the google and facebook providers in our application.

INSTALLED_APPS = [ 
    'django.contrib.admin', 
    'allauth', 
    'allauth.account', 
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google', 
    'allauth.socialaccount.providers.facebook', 
    'django.contrib.auth', 
    'django.contrib.sites', 
    'django.contrib.contenttypes', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
] 

4. Configuring the templates section

Secondly, modify the templates section so that the templates can be supported by the allauth backend.

TEMPLATES = [ 
  { 
        'BACKEND': 'django.template.backends.django.DjangoTemplates', 
        'DIRS': [ 
            os.path.normpath(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', 
                'django.template.context_processors.request', 
            ], 
        }, 
    }, 
]

5. Adding allauth to the Authentication Backends

Thirdly, we’ll need to add allauth so that it can, well… authenticate.

AUTHENTICATION_BACKENDS = ( 
    'django.contrib.auth.backends.ModelBackend', 
    'allauth.account.auth_backends.AuthenticationBackend', 
)

6. Modifying the urls.py in the root folder

Lastly, we’ll modify the urls.py so that we can redirect the user to the accounts page through the Django URL connections.

from django.contrib import admin 
from django.urls import path, include 
urlpatterns = [ 
    path('admin/', admin.site.urls), 
    path('accounts/', include('allauth.urls')), 
]

Upon adding these changes, the functionality of the django-allauth module is functional in the project.

We can access the django-allauth module through the url accounts/ as defined in the urls.py above.

Optional: Working with configuration settings

The settings for the allauth module can be configured and a lot of options are available.

A few of these examples are given below, the rest are available in the Documentation,

# To set up email verification to be mandatory
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS =1
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5
  
# redirects to email if not configured. 
LOGIN_REDIRECT_URL = '/accounts/email/'

Usage of Django-allauth

Working with a basic example with the template redirecting to the allauth accounts view, we are provided with a few options to work with.

Django Allauth
Basic signup page

This gives us a view that allows us to log in to the Django application, through the /accounts/signup/ URL.

In order to work with the features of the social media applications, we’ll need to configure them with the appropriate SOCIALACCOUNT_PROVIDERS.

We’ll also need to create the templates, or you can download them from the official website, to access the pages.

Trying to access the signup page otherwise would result in receiving an error.

In our case, we’ll be working with google and facebook‘s OAUTH providers, so, let’s add it to the settings.py before proceeding further,

SOCIALACCOUNT_PROVIDERS = {
    'facebook': {
        'METHOD': 'oauth2',
        'SDK_URL': '//connect.facebook.net/{locale}/sdk.js',
        'SCOPE': ['email', 'public_profile'],
        'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
        'INIT_PARAMS': {'cookie': True},
        'FIELDS': [
            'id',
            'first_name',
            'last_name',
            'middle_name',
            'name',
            'name_format',
            'picture',
            'short_name'
        ],
        'EXCHANGE_TOKEN': True,
        'LOCALE_FUNC': 'path.to.callable',
        'VERIFIED_EMAIL': False,
        'VERSION': 'v7.0',
    },
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}

It works, and now synchronization and the connection between accounts in the world wide web is preserved!

Conclusion

It’s always quite helpful to learn about new functionality provided by the Django community.

The django-allauth module provides a very useful case of third party authentication support.

It can be modified to allow certain users based on the email domain as well in a more advanced setting.

Deploying Django projects can be a bit hard, so here’s an article that can familiarize you with the tools that are used in the process.

References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages