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

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:
Initiate Login β
/loginredirects to GoogleCallback β
/callbackhandles Googleβs redirect with an auth codeToken Exchange β Exchange code for access + ID tokens
User Info β Fetch profile from Google API
Session Creation β Store user securely in session (signed cookie)
Auth Check β
/mereturns current authenticated userLogout β
/logoutclears the session
π API Endpoints
| Method | Endpoint | Purpose |
| GET | /api/v1/auth/login | Start OAuth flow |
| GET | /api/v1/auth/callback | Handle Google callback |
| GET | /api/v1/auth/logout | Clear user session |
| GET | /api/v1/auth/me | Get 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
Authenticate with Google
Get redirected back with session created
Use
/api/v1/auth/meto check logged-in userLogout anytime using
/api/v1/auth/logout
π§ͺ Testing the Flow
Start login β
/loginRedirect to Google
Callback & token exchange β
/callbackSession stored β
/mereturns profileLogout β
/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
.envconfiguration 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