Python Google Oauth2 Login Integration

Written by

in

Integrating Google OAuth2 login into a Python web application is one of the most effective ways to provide a seamless, secure, and frictionless authentication experience for users. By leveraging Google’s trusted identity platform, developers can offload password management, reduce signup friction, and boost conversion rates—all while keeping their codebase clean and maintainable. In this guide, we’ll walk through the entire process: from setting up a Google Cloud project to implementing OAuth2 in both Flask and Django, handling tokens securely, and troubleshooting common pitfalls. Whether you’re building a small prototype or a production‑grade SaaS, the steps below will give you a solid foundation for Python Google OAuth2 login integration.

Why Choose Google OAuth2 for Your Python App?

  • Trusted security: Google’s infrastructure follows industry‑leading security standards, including multi‑factor authentication and anomaly detection.
  • Reduced password fatigue: Users can sign in with an existing Google account, eliminating the need to remember another password.
  • Rich user profile data: With a single consent screen, you can retrieve email, name, profile picture, and even locale information.
  • Scalable and future‑proof: OAuth2 is the de‑facto standard for modern authentication, making it easy to add other providers later (e.g., Facebook, GitHub).

Prerequisites

  1. Basic knowledge of Python and a web framework (Flask or Django).
  2. Python 3.8+ installed on your development machine.
  3. A Google account to access the Google Cloud Console.
  4. Virtual environment tool (venv, pipenv, or poetry) for dependency isolation.

Step 1: Create a Google Cloud Project and OAuth2 Credentials

1.1 Enable the Google Identity Services API

Log in to the Google Cloud Console, create a new project (or select an existing one), and navigate to APIs & Services > Library. Search for Google Identity Services API and click Enable.

1.2 Configure OAuth Consent Screen

Under APIs & Services > OAuth consent screen, choose External for public apps. Fill in the required fields:

  • App name, support email, and developer contact information.
  • Scopes you need (e.g., email, profile, openid).
  • Authorized domains (e.g., localhost for development, your production domain for live).

Save the consent screen; Google will review it if you request sensitive scopes.

1.3 Generate Client ID and Client Secret

Go to Credentials > Create Credentials > OAuth client ID. Choose Web application and set the following:

  • Authorized JavaScript origins: http://localhost:5000 (Flask) or http://127.0.0.1:8000 (Django).
  • Authorized redirect URIs: http://localhost:5000/auth/callback (Flask) or http://127.0.0.1:8000/oauth2callback/ (Django).

After creation, note the Client ID and Client Secret. Store them securely (e.g., in .env).

Step 2: Install Required Python Packages

Both Flask and Django have mature extensions for OAuth2. The most popular choices are Authlib and python-social-auth. Below we’ll use Authlib for its simplicity and modern API.

pip install Flask Authlib        # For Flask projects
pip install Django Authlib       # For Django projects
pip install python-dotenv        # Optional: load .env files

Step 3: Implement Google OAuth2 in Flask

3.1 Project Structure

.
├─ app.py
├─ templates/
│  ├─ login.html
│  └─ profile.html
└─ .env

3.2 .env File (Never commit secrets)

GOOGLE_CLIENT_ID=YOUR_CLIENT_ID.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=YOUR_CLIENT_SECRET
SECRET_KEY=your_flask_secret_key

3.3 Flask Application Code

from flask import Flask, redirect, url_for, session, render_template, request
from authlib.integrations.flask_client import OAuth
from dotenv import load_dotenv
import os

load_dotenv()  # Load .env variables

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')

# Configure OAuth
oauth = OAuth(app)
google = oauth.register(
    name='google',
    client_id=os.getenv('GOOGLE_CLIENT_ID'),
    client_secret=os.getenv('GOOGLE_CLIENT_SECRET'),
    access_token_url='https://oauth2.googleapis.com/token',
    authorize_url='https://accounts.google.com/o/oauth2/v2/auth',
    client_kwargs={'scope': 'openid email profile'},
)

@app.route('/')
def index():
    user = session.get('user')
    return render_template('login.html', user=user)

@app.route('/login')
def login():
    redirect_uri = url_for('auth_callback', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/auth/callback')
def auth_callback():
    token = google.authorize_access_token()
    resp = google.get('userinfo')
    user_info = resp.json()
    # Store user info in session (or DB for production)
    session['user'] = {
        'id': user_info['sub'],
        'name': user_info['name'],
        'email': user_info['email'],
        'picture': user_info['picture'],
    }
    return redirect(url_for('profile'))

@app.route('/profile')
def profile():
    user = session.get('user')
    if not user:
        return redirect(url_for('index'))
    return render_template('profile.html', user=user)

@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

3.4 Template Snippets

login.html

<!DOCTYPE html>
<html>
<body>
    {% if user %}
        <p>Welcome, <strong>{{ user.name }}</strong>!</p>
        <a href="{{ url_for('profile') }}">View Profile</a>
        <a href="{{ url_for('logout') }}">Logout</a>
    {% else %}
        <a href="{{ url_for('login') }}">Sign in with Google</a>
    {% endif %}
</body>
</html>

profile.html

<!DOCTYPE html>
<html>
<body>
    <h2>User Profile</h2>
    <img src="{{ user.picture }}" alt="Profile picture" width="100">
    <p><strong>Name: {{ user.name }}</p>
    <p><strong>Email: {{ user.email }}</p>
    <a href="{{ url_for('logout') }}">Logout</a>
</body>
</html>

Step 4: Implement Google OAuth2 in Django

4.1 Project Setup

django-admin startproject mysite
cd mysite
python manage.py startapp accounts
pip install django-authlib python-dotenv

4.2 Settings Adjustments (mysite/settings.py)

import os
from dotenv import load_dotenv

load_dotenv()

SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
DEBUG = True
ALLOWED_HOSTS = []

INSTALLED_APPS = [
    # default apps …
    'django.contrib.sessions',
    'accounts',
]

MIDDLEWARE = [
    # default middleware …
    'django.contrib.sessions.middleware.SessionMiddleware',
]

# OAuth2 configuration
GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
GOOGLE_CLIENT_SECRET = os.getenv('GOOGLE_CLIENT_SECRET')

4.3 URL Configuration (mysite/urls.py)

from django.contrib import admin
from django.urls import path, include

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

4.4 Accounts App URLs (accounts/urls.py)

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('login/', views.login, name='login'),
    path('oauth2callback/', views.auth_callback, name='auth_callback'),
    path('profile/', views.profile, name='profile'),
    path('logout/', views.logout_view, name='logout'),
]

4.5 Views Implementation (accounts/views.py)

from django.shortcuts import render, redirect
from django.conf import settings
from authlib.integrations.django_client import OAuth
from django.http import HttpResponse

oauth = OAuth()
google = oauth.register(
name='google',
client_id=settings.GOOGLE_CLIENT_ID,
client_secret=settings.GOOGLE_CLIENT

Comments

Leave a Reply

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