Add Google Gmail Login to Django Website using django-allauth

In today’s digital age, user authentication is a crucial part of web development. Instead of creating and managing your authentication system from scratch, integrating third-party authentication providers like Gmail can save you time and enhance user convenience. In this tutorial, we will walk you through the process of adding Gmail login to your Django website with a practical example.

Prerequisites:

  1. Basic knowledge of Django.
  2. A Django project up and running.

Let’s get started!

Step 1: Create a Django Project

If you haven’t already, create a Django project using the following command:

django-admin startproject myproject

Recommeded: Please read our blog, on how we create Basic Django Project

Step 2: Set Up Your Django Application

Create a Django app within your project:

cd myproject
python manage.py startapp myapp

Add your app to the INSTALLED_APPS list in myproject/settings.py:

INSTALLED_APPS = [
    # ...
    'myapp',
    # ...
]

Step 3: Configure Gmail API

To enable Gmail login, you’ll need to create a project on the Google Developers Console and set up OAuth 2.0 credentials.

  1. Go to the Google Developers Console.
  2. Create a new project or select an existing one.
  3. In the project dashboard, go to “Credentials.”
  4. Click on “Create Credentials” and choose “OAuth client ID.”
  5. Select “Web application” as the application type.
  6. Under ‘Authorized JavaScript origins’, add the following URIs:
    http://localhost:8000
    http://127.0.0.1:8000
  7. Under ‘Authorized redirect URIs’, add the following URIs:
    http://127.0.0.1:8000/accounts/google/login/callback/
    http://localhost:8000/accounts/google/login/callback/
  8. Click “Create” and note down your “Client ID” and “Client Secret.” We’ll use these later.
Watch this video to create OAuth Client Id and Secret in Google Account

Step 4: Install Required Libraries

You’ll need to install some Python libraries to handle OAuth2 authentication and Gmail integration. Run the following commands:

pip install django-allauth

Step 5: Configure Django Allauth

Add 'allauth' and 'allauth.account' to the INSTALLED_APPS and MIDDLEWARE list in your settings.py file:

INSTALLED_APPS = [
    # ...
    'myapp', # Your App
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    # ...
]

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',
    'allauth.account.middleware.AccountMiddleware',
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',  # Default ModelBackend
    'allauth.account.auth_backends.AuthenticationBackend',  # Allauth authentication backend for social authentication
]

LOGIN_REDIRECT_URL = '/'
ACCOUNT_EMAIL_VERIFICATION = 'none'

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'APP': {
            'client_id': 'YOUR_CLIENT_ID',
            'secret': 'YOUR_CLIENT_SECRET',
            'key': ''
        }
    }
}

Replace 'YOUR_CLIENT_ID' and 'YOUR_CLIENT_SECRET' with the values you obtained from the Google Developers Console.

Step 6: Create a Custom User Model (Optional)

The default Django User model includes fields like username, email, and password, which cover the basics of user authentication and management. However, real-world applications often demand more user-specific attributes and functionalities. Imagine a scenario where you’re building a social platform or an e-commerce site. You might need to store user profiles, social media links, user avatars, or even track user activity.

Learn more about How to Extend the Django User Model: Exploring Various Approaches

Step 9: Update URLs

In your myproject/urls.py file, add the following URL patterns:

from django.urls import path, include

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

Step 9: Create Templates (Optional)

Create templates for login and account management in the myapp/templates/ directory, following Allauth’s templates structure.

Step 10: Migrate and Run the Server

Run the following commands to apply migrations and start the development server:

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Visit http://localhost:8000/accounts/login/ to see your Gmail login in action.

You can also check the users account list in Django Admin. Create a superuser – python manage.py createsuper and go to http://localhost:8000/admin/

Congratulations! You’ve successfully added Gmail login to your Django website. Users can now sign in with their Gmail accounts, saving them the hassle of creating yet another username and password.

Remember to handle user data and permissions responsibly when integrating third-party authentication. This ensures the privacy and security of your users’ information while providing a seamless login experience.

Read Next: Learn how to protect your CLIENT ID AND SECRET in python project.

Find this tutorial on Github.

Also check our blog for Github and Facebook Login

Blogs You Might Like to Read!