Integrating Google OAuth2 login into a Python web application is a powerful way to boost user experience, improve security, and leverage Google’s trusted authentication system. Whether you’re building a small Flask prototype or a full‑featured Django portal, the process follows a clear set of steps that can be mastered quickly. In this guide we’ll walk through everything you need—from creating a Google API project and configuring credentials, to writing clean Python code that handles the OAuth2 flow, validates tokens, and securely logs users in. By the end, you’ll have a production‑ready implementation that not only simplifies sign‑ups but also enhances SEO with relevant keywords like “Python Google OAuth2 login integration.”
What Is OAuth2 and Why Use Google for Authentication?
OAuth2 is an open standard for access delegation, allowing users to grant limited access to their resources without sharing passwords. Google’s OAuth2 service is especially popular because:
- Trust: Users already trust Google’s login UI, reducing friction.
- Security: Tokens are short‑lived and can be revoked at any time.
- Rich Profile Data: With the appropriate scopes you can fetch the user’s email, name, and profile picture.
- SEO Benefits: Implementing a modern authentication flow signals a well‑maintained site to search engines.
Step 1: Create a Google Cloud Project and OAuth2 Credentials
1.1 Open the Google Cloud Console
Navigate to Google Cloud Console and sign in with a Google account that has project‑creation rights.
1.2 Set Up a New Project
- Click New Project and give it a descriptive name (e.g.,
MyPythonApp‑OAuth). - Choose an organization or keep it under “No organization.”
- Click Create and wait for the project to provision.
1.3 Enable the “Google+ API” (or “People API” for newer implementations)
From the left navigation, select APIs & Services > Library, search for “People API,” and click Enable. This API provides the profile information you’ll request.
1.4 Create OAuth2 Client ID
- Go to APIs & Services > Credentials and click Create Credentials > OAuth client ID.
- Choose Web application as the application type.
- Enter a name like
PythonOAuthClient. - Under Authorized redirect URIs, add the URL where Google should send the auth response (e.g.,
http://localhost:5000/auth/callbackfor Flask orhttp://localhost:8000/accounts/google/login/callback/for Django). - Click Create. Copy the Client ID and Client Secret – you’ll need them in your Python code.
Step 2: Install Required Python Packages
Both Flask and Django have dedicated extensions that simplify the OAuth2 flow. Install the core libraries using pip:
pip install requests
pip install google-auth
pip install google-auth-oauthlib
# Flask specific
pip install Flask Flask-Login Flask-OAuthlib
# Django specific
pip install Django social-auth-app-django
These packages handle token exchange, session management, and user model integration, letting you focus on business logic.
Step 3: Implement Google OAuth2 in Flask
3.1 Basic Flask App Skeleton
from flask import Flask, redirect, url_for, session, request
from flask_oauthlib.client import OAuth
app = Flask(__name__)
app.secret_key = 'YOUR_RANDOM_SECRET_KEY'
oauth = OAuth(app)
google = oauth.remote_app(
'google',
consumer_key='YOUR_CLIENT_ID',
consumer_secret='YOUR_CLIENT_SECRET',
request_token_params={
'scope': 'email profile'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://oauth2.googleapis.com/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
)
3.2 Login Route
@app.route('/login')
def login():
return google.authorize(
callback=url_for('authorized', _external=True)
)
3.3 Authorization Callback
@app.route('/auth/callback')
def authorized():
resp = google.authorized_response()
if resp is None or resp.get('access_token') is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
session['google_token'] = (resp['access_token'], '')
user_info = google.get('userinfo')
# Example: store user info in session
session['user'] = {
'email': user_info.data['email'],
'name': user_info.data['name'],
'picture': user_info.data['picture']
}
return redirect(url_for('profile'))
3.4 Token Getter
@google.tokengetter
def get_google_oauth_token():
return session.get('google_token')
3.5 Protected Profile Page
@app.route('/profile')
def profile():
if 'user' not in session:
return redirect(url_for('login'))
user = session['user']
return f\"\"\"<h2>Welcome, {user['name']}!</h2>
<img src='{user['picture']}' alt='Profile picture'>
<p>Email: {user['email']}</p>\"\"\"
Run the app with flask run, visit /login, and you’ll be redirected to Google’s consent screen. After granting access, the user lands on the profile page with their Google data.
Step 4: Implement Google OAuth2 in Django Using Social‑Auth
4.1 Configure Settings
# settings.py
INSTALLED_APPS = [
# … default apps …
'social_django',
]
AUTHENTICATION_BACKENDS = (
'social_core.backends.google.GoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'YOUR_CLIENT_ID'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'YOUR_CLIENT_SECRET'
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'profile'
LOGOUT_REDIRECT_URL = 'home'
# Optional: request extra profile fields
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email', 'profile']
SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = ['first_name', 'last_name']
4.2 URL Configuration
# urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('profile/', views.profile, name='profile'),
path('auth/', include('social_django.urls', namespace='social')),
]
4.3 Simple Views
# views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'home.html')
@login_required
def profile(request):
user = request.user
# Social auth stores extra data in user.social_auth
extra = user.social_auth.get(provider='google-oauth2')
context = {
'email': user.email,
'name': extra.extra_data.get('name'),
'picture': extra.extra_data.get('picture')
}
return render(request, 'profile.html', context)
4.4 Template Snippet for Login
<a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">
Sign in with Google
</a>
After adding the templates, run python manage.py migrate to create the required tables, then start the server. Clicking the “Sign in with Google” link launches the OAuth2 flow, and Django automatically creates or updates the user record.
Step 5: Validate Tokens and Secure Your Integration
Even though Google handles most of the heavy lifting, you should still verify the ID token on the server side to protect against token replay attacks.
- Use
google.oauth2.id_token.verify_oauth2_token()to decode and validate the token. - Check the
aud(audience) claim matches your client ID. - Confirm the token has not expired (
expclaim).
from google.oauth2 import id_token
from google.auth.transport import requests
def verify_token(id_token_str):
try:
idinfo = id_token.verify_oauth2_token(
id_token_str,
requests.Request(),
'YOUR_CLIENT_ID
Leave a Reply