Skip to main content

Command Palette

Search for a command to run...

πŸš€ FastAPI With Google OAuth 2.0 And CORS, CSRF Protection, Secure Cookies

Updated
β€’3 min read
πŸš€ FastAPI With Google OAuth 2.0  And CORS, CSRF Protection, Secure Cookies
K

Passionate developer with a keen interest in solving real-world problems using efficient algorithms. I write about Java, data structures, and algorithmic challenges, focusing on performance and simplicity. Currently exploring cloud computing, DevOps, and building web apps with React.js. On a journey to help others with tips and insights from my coding adventures. Let’s code and grow together!

When building modern web applications, authentication is one of the most critical pieces. With users demanding secure, seamless, and reliable login flows, integrating Google OAuth 2.0 becomes a popular choice.

In this article, I’ll walk you through a secure Google OAuth 2.0 implementation using FastAPI, Authlib, and session-based authentication, with all the right security measures like CSRF protection, secure cookies, and environment-based configurations.

βœ… Features

  • πŸ” Google OAuth 2.0 Integration

  • 🧠 Session-Based Authentication (no JWT headaches)

  • πŸ›‘οΈ CSRF Protection using OAuth2 State parameter

  • 🌍 CORS Configuration for frontend support

  • πŸ”§ Manual Token Exchange (no hidden Authlib bugs)

  • πŸ“¦ Environment-based Config with .env

  • ❌ Secure Cookie Management with HttpOnly + Secure flags

  • βœ… Error Handling & Validation for safe user flows

πŸ› οΈ Tech Stack

  • Backend Framework β†’ FastAPI (lightning-fast Python web framework)

  • Authentication & OAuth β†’ Authlib + Google OAuth 2.0

  • Session Management β†’ Starlette Sessions + ItsDangerous (secure cryptographic cookies)

  • HTTP & Async β†’ Uvicorn + HTTPX

  • Configuration β†’ Pydantic + python-dotenv

  • Security β†’ CORS, CSRF Protection, Secure Cookies

πŸ” OAuth 2.0 Flow

Here’s how the Google OAuth 2.0 login works in this project:

  1. Initiate Login β†’ /login redirects to Google

  2. Callback β†’ /callback handles Google’s redirect with an auth code

  3. Token Exchange β†’ Exchange code for access + ID tokens

  4. User Info β†’ Fetch profile from Google API

  5. Session Creation β†’ Store user securely in session (signed cookie)

  6. Auth Check β†’ /me returns current authenticated user

  7. Logout β†’ /logout clears the session

🌐 API Endpoints

MethodEndpointPurpose
GET/api/v1/auth/loginStart OAuth flow
GET/api/v1/auth/callbackHandle Google callback
GET/api/v1/auth/logoutClear user session
GET/api/v1/auth/meGet current authenticated user

βš™οΈ Setup & Installation

Clone the repo and install dependencies:

git clone https://github.com/kuldeepghorpade05/Google_OAuth_with_FastAPI.gi
cd fastapi-google-oauth
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

πŸ”‘ Environment Variables

Create a .env file in the root directory:

GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
SECRET_KEY=your_random_secret_key
SESSION_COOKIE_NAME=fastapi_session
BASE_URL=http://localhost:8000
ALLOWED_ORIGINS=http://localhost:3000

πŸš€ Running the App

uvicorn app.main:app --reload

Now open:
πŸ‘‰ http://localhost:8000/api/v1/auth/login

  1. Authenticate with Google

  2. Get redirected back with session created

  3. Use /api/v1/auth/me to check logged-in user

  4. Logout anytime using /api/v1/auth/logout

πŸ§ͺ Testing the Flow

  • Start login β†’ /login

  • Redirect to Google

  • Callback & token exchange β†’ /callback

  • Session stored β†’ /me returns profile

  • Logout β†’ /logout

πŸ”’ Why This Matters

Authentication is often the weakest link in security. By using:

  • Sessions (instead of exposing JWT in localStorage)

  • CSRF Protection (via state parameter)

  • Secure Cookies (HttpOnly + Secure flags)

…you ensure your FastAPI app is both user-friendly and highly secure.

🎯 Final Thoughts

This project demonstrates a production-ready Google OAuth 2.0 implementation in FastAPI with:

  • Strong session security

  • Clean, modular architecture

  • Frontend-friendly CORS setup

  • Easy .env configuration for different environments

πŸ‘‰ Perfect for SaaS apps, dashboards, or any project requiring Google login.

πŸ“‚ Source Code

You can check out and fork the full project on GitHub here:

πŸ‘‰ Fork on GitHub -> https://github.com/kuldeepghorpade05/Google_OAuth_with_FastAPI.git

Connect with me