How to Build a Social Authentication System in Django Using OAuth

Trending 2 months ago

Social authentication is simply a measurement to corroborate a person’s personality done a societal relationship alternatively of utilizing passwords. In web development, it is ever adjuvant to authenticate users without passwords. This way, they tin log successful done societal apps for illustration Google, Twitter, aliases GitHub.

Enabling societal authentication is simply a awesome measurement to heighten your application’s information by reducing nan consequence of communal password-related vulnerabilities. It will besides amended nan personification acquisition of your app because users will not request to retrieve galore passwords.

User Authentication successful Django

Django provides a default authentication strategy for developers to activity with. However, this authentication strategy uses accepted authentication, which involves manually collecting information specified arsenic nan username, email, password, first name, and past sanction of nan user.

By design, Django's authentication strategy is very generic and does not supply galore features utilized successful astir web authentication systems today. To complement this, you'll want to usage third-party packages specified arsenic nan django-allauth package.

How to Enable OAuth successful Django

To authenticate your users utilizing OAuth successful a Django application, you tin usage a Django package called django-allauth.

Django Allauth is simply a package that handles authentication, registration, relationship management, and third-party (social) relationship authentication for your Django project. The pursuing steps will guideline you toward mounting up Django Allauth for your Django project.

Step 1: Install and Set Up Django-Allauth

If you are yet to do so, create a virtual environment and instal django-allauth via pip:

pip instal django-allauth

Note that you must beryllium utilizing Python 3.5 aliases higher and Django 2.0 aliases higher for it to work.

Step 2: Add Required Apps to Django for Django-Allauth

After installing django-allauth, unfastened your settings.py record and adhd nan pursuing apps to your INSTALLED_APPS list:

INSTALLED_APPS = [

    """
    Add your different apps here
    """

    
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
]

Here are immoderate points to statement astir immoderate of nan supra apps:

  • The allauth.socialaccount app will fto users motion successful done societal apps specified arsenic X (formerly Twitter), Instagram, GitHub, and others.
  • The django.contrib.sites app is simply a built-in Django model that's required for django-allauth to work. The app provides nan expertise to negociate and differentiate aggregate sites wrong a azygous Django project. You tin understand really it useful by referring to nan Django documentation.

Step 3: Define nan Authentication Backends for Your Project

The adjacent measurement is to specify really you want to authenticate your users. You tin do this by configuring nan AUTHENTICATION_BACKENDS successful your settings.py file. For django-allauth, you should adhd these:

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

The codification snippet supra defines 2 authentication backends:

  1. The first 1 is nan default 1 utilized by Django. This will let nan admin personification to log successful to nan admin sheet irrespective of django-allauth's configuration.
  2. The 2nd 1 defines nan authentication backend for django-allauth.

Step 4: Add Your Site ID

In your settings file, you should adhd nan ID for your site. Here's an example:

SITE_ID = 1

By default, location is simply a tract called example.com successful nan admin panel. You tin determine to modify this tract aliases adhd 1 for yourself. In either case, you should log successful to nan admin sheet and navigate to nan Sites app.

django admin sheet to adhd a caller site

To get nan tract ID for a Django site, unfastened up your Command Line Interface (CLI) and tally this command:

python manage.py shell

Next, constitute this book into nan Python shell:

from django.contrib.sites.models import Site

current_site = Site.objects.get_current()
site_id = current_site.id
site_name = current_site.name
print("Site ID:", site_id)
print("Site Name:", site_name)

The supra codification will people nan sanction of nan tract arsenic good arsenic its ID.

Step 5: Configure Your URLs

In your project's urls.py file, configure nan URL shape for django-allauth. This is really it should look like:

from django.urls import path, include

urlpatterns = [
    
    path('accounts/', include('allauth.urls')),
]

With this setup, you tin commencement your improvement server and navigate to http://127.0.0.1:8000/accounts/. If you person DEBUG group to True, you should spot a database of disposable URL patterns for django-allauth.

A 404 page successful Django DEBUG mode, showing a database of URL patterns disposable successful django-allauth

If you person done nan above, your task should beryllium fresh for societal authentication.

How to Implement Google Login/Signup successful Your Django App

After mounting up django-allauth, you should beryllium fresh to fto your users authenticate themselves pinch their societal accounts specified arsenic Google.

In your settings.py file, you should adhd nan societal relationship supplier successful INSTALLED_APPS. In this case, it is Google. Other options are Instagram, X, etc.

INSTALLED_APPS = [

    """
    Add your different apps here
    """

    
    'allauth.socialaccount.providers.google',
]

Step 2: Create Your Client ID and Secret Key connected Google

To complete this step, you must person a Google relationship created. If you person done so, travel these adjacent steps:

  1. Head complete to nan Google Cloud console to create a caller project. First, click connected nan drop-down shown successful nan image below:
    Google unreality console interface
  2. Next, click connected NEW PROJECT:
    Google unreality console page for creating a caller project
  3. Enter a sanction for your project, past click nan CREATE button:
    Google unreality console page for entering nan sanction of a caller project
  4. With your task selected, click connected the hamburger menu. Select APIs & Services, past Credentials:
    Google unreality console credentials option
  5. Next, click connected nan action that says CONFIGURE CONSENT SCREEN and prime External:
    Google unreality interface for creating a consent screen
  6. On nan adjacent page, participate a sanction for your app and see an email wherever necessary. You tin besides research nan configurations for immoderate customization. Once done, click connected SAVE AND CONTINUE.
    A shape to participate nan email reside and app sanction for your consent screen
  7. On nan left-hand menu, prime Credentials. After that, click connected CREATE CREDENTIALS and prime OAuth customer ID.
    Creating a caller group of oauth customer id credentials
  8. Next, prime nan Application type and participate a sanction for nan same. For this tutorial, nan Application type will beryllium Web application.
    A shape to prime nan applicating type and sanction for your caller OAuth customer ID credentials
  9. Next, adhd URIs for nan Authorized JavaScript origins and Authorized redirect URIs. Your website's big should beryllium nan JavaScript origins, and nan strategy will redirect users to nan redirect URI aft authentication. The redirect URI should typically incorporate your-host-name/accounts/google/login/callback/. For improvement mode, it'll be: http://127.0.0.1:8000/accounts/google/login/callback/. Click connected CREATE erstwhile once done.
    Adding nan basal URIs for nan Authorized JavaScript origins and Authorized redirect URIs
  10. After creating nan credentials, you tin transcript your Client ID aliases Client secret to a safe spot aliases download them arsenic JSON files.
    Copy aliases download your OAuth credentials

Step 3: Add Your Client ID and Secret Key to Your Django App

After creating nan basal credentials, navigate to http://127.0.0.1:8000/admin, prime Social applications, and create a caller societal application. Follow these steps to create a caller societal app:

  1. Add a provider. The supplier refers to nan app you're authenticating your personification with. In this case, it is Google, successful different case, it mightiness beryllium Snapchat.
  2. Enter a sanction for your caller societal app. Make judge it is simply a reasonable sanction
  3. Paste successful nan Client ID you copied from Google.
  4. For nan Secret key, paste successful nan Client secret you copied from Google.
  5. The Key section does not use to authentication pinch Google, truthful disregard it.
  6. Finally, prime a tract to subordinate nan societal exertion with.
Add your caller OAuth credentials to your admin panel

Step 4: Test Your Google Authentication

Log retired of your admin sheet and navigate to http://127.0.0.1:8000/accounts/login/. You'll spot an action to log successful via Google.

Django-Allauth's default motion successful page

Click connected it to redirect to nan consent screen. Next, prime an relationship to log successful with.

Google consent screen

Once you person selected an account, you'll get redirected to http://127.0.0.1:8000/accounts/profile/. This intends your app is moving perfectly. You tin create civilization templates to switch nan default ones.

Enabling societal authentication is simply a awesome measurement to thief your users person a awesome acquisition registering for your application. There are different ways to alteration authentication successful Django, and you should research them to determine what's champion for your usage case.

Source Tutorials
Tutorials