Django Google Authentication

I’ve been working as a Python developer for many years, and one thing I’ve learned is that integrating third-party authentication can be a game-changer for your app’s user experience and security. Google Authentication, in particular, is widely used by users in the USA and worldwide, making it a smart choice for any Django project.

In this article, I’ll walk you through exactly how to set up Google Authentication in your Django application. I’ll share two effective methods based on my own experience: using the popular django-allauth package and implementing OAuth2 manually with social-auth-app-django. Both approaches are straightforward, and I’ll provide full code examples so you can pick what suits your project best.

Let’s get started!

Why Use Google Authentication in Django?

Google Authentication allows your users to log in using their Google accounts, eliminating the need to create and remember new passwords. This not only improves security but also boosts user engagement by simplifying the sign-in process.

From my experience working with clients across the USA, integrating Google OAuth2 has helped reduce login friction and increased trust in applications, especially those handling sensitive data or requiring compliance with security standards.

Read Compare Two Integers in Python Django

Method 1: Use django-allauth for Google Authentication

django-allauth is a robust and widely used package that supports multiple authentication providers, including Google. It handles most of the heavy lifting for you, such as token management, user registration, and social account linking.

Step 1: Install Required Packages

First, install django-allauth using pip:

pip install django-allauth

Step 2: Configure Installed Apps

In your Django project’s settings.py, add the following apps:

INSTALLED_APPS = [
    # Default Django apps...
    'django.contrib.sites',

    # Allauth apps
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

SITE_ID = 1

Step 3: Add Authentication Backends

Still in settings.py, set the authentication backends:

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

Step 4: Configure Google OAuth Credentials

Head over to the Google Cloud Console and create OAuth 2.0 credentials:

  • Create a new project or select an existing one.
  • Navigate to APIs & Services > Credentials.
  • Click Create Credentials > OAuth client ID.
  • Choose Web application.
  • Add your authorized redirect URIs, e.g., http://localhost:8000/accounts/google/login/callback/.
  • Save the client ID and secret.

Step 5: Add Social Account Settings

Add your Google client ID and secret to settings.py:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': ['profile', 'email'],
        'AUTH_PARAMS': {'access_type': 'online'},
        'CLIENT_ID': 'YOUR_GOOGLE_CLIENT_ID',
        'SECRET': 'YOUR_GOOGLE_CLIENT_SECRET',
    }
}

Check out Payment Gateway Integration with Django

Step 6: Update URLs

In your project’s urls.py, add:

from django.urls import path, include

urlpatterns = [
    # Your other URLs...
    path('accounts/', include('allauth.urls')),
]

Step 7: Run Migrations and Start Server

Run migrations to create necessary tables:

python manage.py migrate
python manage.py runserver

Step 8: Test Google Login

Visit http://localhost:8000/accounts/login/ and you’ll see a Google login option. Clicking it will redirect you to Google’s OAuth consent screen. After successful authentication, you’ll be redirected back to your app, logged in with your Google account.

You can see the output in the screenshot below.

django google auth

This is the default login form provided by Django Allauth.

google Django
django google

Read How to Add Items to Cart in Django in Python?

Method 2: Use social-auth-app-django for Google OAuth2

If you prefer more control or want to customize the authentication flow, social-auth-app-django is a great alternative. It’s flexible and supports many social login providers.

Step 1: Install the Package

pip install social-auth-app-django

Step 2: Update settings.py

Add the app to INSTALLED_APPS:

INSTALLED_APPS = [
    # Default apps...
    'social_django',
]

Add authentication backends:

AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

Add Google OAuth2 keys:

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'YOUR_GOOGLE_CLIENT_ID'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'YOUR_GOOGLE_CLIENT_SECRET'

Add login redirect URLs:

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

Add social auth context processors to your templates:

TEMPLATES = [
    {
        # ...
        'OPTIONS': {
            'context_processors': [
                # ...
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

Step 3: Update URLs

In your main urls.py:

from django.urls import path, include
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/', include('social_django.urls', namespace='social')),
    path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

Check out if Python Dictionary is Empty

Step 4: Create a Simple Login Template

Create a templates/login.html file:

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <a href="{% url 'social:begin' 'google-oauth2' %}">Login with Google</a>
</body>
</html>

Step 5: Run Migrations and Start Server

python manage.py migrate
python manage.py runserver

Step 6: Test Google Login

Open http://localhost:8000/login/ and click the “Login with Google” link. You’ll be redirected to Google and back after authentication.

You can see the output in the screenshot below.

django google authentication
django google login

Read Python Filter Not in Django

Tips from My Experience

  • Always configure your OAuth credentials carefully, especially redirect URIs. A mismatch here is the most common cause of errors.
  • Use environment variables or Django’s decouple package to keep your client secrets safe.
  • Test your authentication flow locally before deploying.
  • For production, ensure you use HTTPS URLs in Google Cloud Console.
  • Customize user models if you want to store additional data from Google’s profile.

Integrating Google Authentication into your Django app doesn’t have to be complicated. Whether you choose django-allauth for ease or social-auth-app-django for flexibility, both methods provide solid foundations to secure your app and improve user experience.

If you have any questions or want me to cover other authentication providers, feel free to leave a comment below!

Other Python Articles You May Like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.