Wednesday, 22 October 2025

#18 gmail AUthentication

Gmail Authentication with Django: Step-by-Step Tutorial

Gmail Authentication in Django: Step-by-Step Tutorial

Learn how to set up Gmail (Google) authentication on your Django site using the popular third-party package django-allauth. This method lets users log in or sign up with their Google account in a secure, scalable way.

Step 1: Install Required Packages

pip install django-allauth

Step 2: Add Apps and Settings in settings.py

INSTALLED_APPS = [
    # Django default apps...
    "django.contrib.sites",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
]

SITE_ID = 1

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

LOGIN_REDIRECT_URL = "/"

Step 3: Add Allauth URLs to Project

# mysite/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
]

Step 4: Create a Google OAuth App

  • Go to Google Cloud Console > APIs & Services > Credentials
  • Create a new OAuth Client ID (Web application)
  • Add authorized redirect URI: http://localhost:8000/accounts/google/login/callback/
  • Save your Client ID and Secret.

Step 5: Configure Google Provider in Django Admin

  1. Run the server and log in to /admin
  2. Find Sites and make sure domain is localhost
  3. Find Social applications and add Google:
    • Provider: Google
    • Name: Google
    • Client ID: (your Google client ID)
    • Secret Key: (your Google secret)
    • Sites: Select your current site

Step 6: Customizing Login Button in Template

<a href="{% provider_login_url 'google' %}">
  Login with Google
</a>

Step 7: Try It Out!

  • Visit /accounts/login/ and click Login with Google
  • Authenticate with your Gmail account
  • Get redirected to your app, now signed in!

Extra: Customizing Forms, User Model, and Redirects

  • Override templates in templates/account/
  • Extend user model for extra fields if needed
  • Change LOGIN_REDIRECT_URL for custom flows
With django-allauth, you can add many other social providers easily (Facebook, Twitter, etc).

No comments:

Post a Comment

#20b Python (run+edit in browser ^ all in one)

๐Ÿ Python Basics — 5 Interactive Modules Edit code live with syntax highlighting and click ▶ Run . Each module runs separately ...