Integrating Google’s OAuth 2.0 authentication into a Python web application is one of the most effective ways to provide a seamless, secure login experience for users. Not only does it eliminate the need for custom password management, but it also leverages Google’s trusted identity platform, boosting user confidence and reducing friction. In this guide we’ll walk through the entire process—from setting up a Google Cloud project to implementing the login flow with popular Python frameworks such as Flask and Django—while keeping SEO best practices in mind so your article ranks high for “Python Google OAuth2 login integration”.
Why Choose Google OAuth 2.0 for Python Applications?
- Security: Google handles password storage, multi‑factor authentication, and token revocation, protecting both you and your users.
- Speed to market: With ready‑made libraries (e.g.,
google-auth,oauthlib) you can get a functional login screen up in minutes. - Universal access: Millions of users already have a Google account, so the barrier to entry is minimal.
- Scalability: OAuth 2.0 tokens are stateless, making it easy to scale horizontally without complex session stores.
Prerequisites Before You Start
- A Google account with access to the Google Cloud Console.
- Python 3.8+ installed on your development machine.
- Basic familiarity with a Python web framework (Flask or Django).
- Virtual environment tool (e.g.,
venvorconda).
Step 1: Create a Google Cloud Project and OAuth 2.0 Credentials
All OAuth 2.0 flows start with a project in the Google Cloud Console. Follow these steps to generate the required client ID and client secret.
- Log into the Google Cloud Console and click New Project.
- Give the project a descriptive name (e.g., MyPythonApp‑OAuth) and click Create.
- Navigate to APIs & Services > Credentials → Create Credentials → OAuth client ID.
- Select Web application as the application type.
- Under Authorized redirect URIs, add the URL where Google will send the authentication response. For local development use:
http://localhost:5000/auth/callbackAdjust the port and path according to your framework’s routing.
- Click Create. Google will display a Client ID and Client Secret. Save these values securely; you’ll need them in your Python code.
Step 2: Install Required Python Packages
Both Flask and Django have mature extensions that wrap the OAuth 2.0 flow. The following packages work for most use‑cases:
pip install Flask Flask-Dance
# or for Django
pip install Django social-auth-app-django
# common utilities
pip install google-auth google-auth-oauthlib requests
Step 3: Implementing Google OAuth 2.0 with Flask
3.1 Basic Flask App Structure
from flask import Flask, redirect, url_for, session
from flask_dance.contrib.google import make_google_blueprint, google
app = Flask(__name__)
app.secret_key = "super‑secret‑key" # replace with a strong random value
# Configure the Google OAuth blueprint
google_bp = make_google_blueprint(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET",
scope=["profile", "email"],
redirect_url="/auth/callback"
)
app.register_blueprint(google_bp, url_prefix="/login")
3.2 Protecting Routes and Retrieving User Info
@app.route("/")
def index():
if not google.authorized:
return redirect(url_for("google.login"))
resp = google.get("/oauth2/v2/userinfo")
assert resp.ok, resp.text
user_info = resp.json()
return f"Hello, {user_info['name']}! Your email is {user_info['email']}."
@app.route("/logout")
def logout():
# Revoke token and clear session
token = google_bp.token["access_token"]
google.post(
"https://accounts.google.com/o/oauth2/revoke",
params={"token": token},
headers={"content-type": "application/x-www-form-urlencoded"}
)
del session["google_oauth_token"]
return redirect(url_for("index"))
3.3 Running the App
if __name__ == "__main__":
app.run(debug=True)
Visit http://localhost:5000/ and you’ll be redirected to Google’s login page. After granting permission, Google sends the user back to /auth/callback, and the Flask‑Dance blueprint exchanges the authorization code for an access token.
Step 4: Implementing Google OAuth 2.0 with Django
4.1 Configure settings.py
# settings.py
INSTALLED_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 = "home"
LOGOUT_REDIRECT_URL = "login"
# Optional: request additional profile fields
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ["email", "profile"]
SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = ["first_name", "last_name"]
4.2 Update URLs
# urls.py
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
path("admin/", admin.site.urls),
path("login/", auth_views.LoginView.as_view(), name="login"),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path("oauth/", include("social_django.urls", namespace="social")),
path("", views.home, name="home"),
]
4.3 Create a Simple Home View
# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
user = request.user
return render(request, "home.html", {"user": user})
4.4 Template Example (home.html)
<!DOCTYPE html>
<html>
<head>
<title>Welcome {{ user.get_full_name }}</title>
</head>
<body>
<h2>Hello, {{ user.first_name }}!</h2>
<p>Your Google email is {{ user.email }}.</p>
<a href="{% url 'logout' %}">Logout</a>
</body>
</html>
When a user clicks the “Login with Google” button (you can add it with {% url 'social:begin' 'google-oauth2' %}), Django redirects to Google, handles the callback, creates or updates a User object, and logs the user in automatically.
Step 5: Handling Tokens, Refresh, and Revocation
OAuth 2.0 access tokens typically expire after one hour. Google also provides a refresh token (if you request access_type=offline) that can be used to obtain a new access token without user interaction. Both Flask‑Dance and Django‑Social‑Auth abstract this logic, but understanding the underlying flow helps you troubleshoot issues.
- Storing refresh tokens: Never store them in plain text. Use encrypted fields or a secrets manager.
- Automatic refresh: The libraries automatically call
google-auth-oauthlib.flow.InstalledAppFlowor the Django backend to refresh the token when an API request fails with401 Unauthorized. - Revocation: Provide a logout endpoint that calls Google’s revocation endpoint (as shown in the Flask example) to invalidate the token on Google’s side.
Step 6: Security Best Practices for Production
- Use HTTPS: OAuth 2.0 requires secure transport for the redirect URI. Deploy behind a TLS‑terminated load balancer or use services like Let’s Encrypt.
- Validate the
stateparameter: Both Flask‑Dance and Django‑Social‑Auth generate a randomstatetoken to protect against CSRF attacks. Never disable this feature. - Restrict scopes: Only request the data you truly need (e.g.,
emailandprofile). Excessive scopes can trigger privacy concerns and may lead to app verification delays. - Enable App Verification: If your app requests sensitive or restricted scopes, Google will require a verification process. Plan for it early to avoid launch delays.
- Rotate secrets regularly: Treat the client secret like a password. Rotate it in the Google Cloud Console and update your environment variables accordingly.
Leave a Reply