A Universal Authentication Module for Python FastAPI on Google Cloud Platform (GCP). This addon provides a drop-in implementation of Role-Based Access Control (RBAC) using Firebase Auth and Firestore.
Designed as a portable application-layer alternative to Google Cloud Identity-Aware Proxy (IAP), it allows you to secure apps across Localhost, VPS, and Cloud Run using the same "Auth Environment" logic. Define user "buckets" (e.g., alpha, prod) in Firestore and dynamically restrict access without infrastructure changes.
This addon is designed as an Embedded Library, not a separate microservice/proxy. It lives inside your FastAPI application.
- Hybrid Authentication:
- Frontend: Uses Firebase JS SDK for a seamless Google Sign-In popup flow.
- Backend: Exchanges ID Tokens for secure Session Cookies (valid for up to 2 weeks), managed by the Firebase Admin SDK.
- Environment-Based RBAC:
- Define user access lists in Firestore documents (e.g.,
auth_environments/dev,auth_environments/prod). - Services "subscribe" to a specific environment via the
AUTH_ENVIRONMENTvariable.
- Define user access lists in Firestore documents (e.g.,
- Drop-In Ready: Modular
dependencies.pyandroutes/auth.pycan be copied into any FastAPI project. - Developer Friendly: Includes automation scripts (
run_dev.py) to inject credentials and config from a local file, keeping secrets out of source control.
This addon fills a specific gap in the GCP ecosystem for developers managing multiple environments (Personal, Dev, Prod).
| Solution | Best Used For | Limitation | How this Addon Compares |
|---|---|---|---|
| Identity-Aware Proxy (IAP) | Zero-trust protection for internal apps. | Requires Load Balancer (cost) or Org constraints; hard to use locally. | Application-Layer equivalent. Works on Localhost, standard Cloud Run, and VPS without LB overhead. |
| Client-Side Firebase Auth | SPAs and Mobile Apps. | Tokens handle client-side only; insecure for backend rendering or strict API access control. | Upgrades to Server-Side Sessions. Uses HttpOnly cookies for secure backend authenticaton (Jinja2 friendly). |
| Workforce Identity Federation | Federated Enterprise Auth (Azure AD, Okta). | Complex setup; overkill for alpha/beta buckets or Google-centric teams. | Modular Foundation. Start with this simple Google Auth now; the dependencies.py layer is ready to wrap WIF headers later if needed. |
.
├── app.py # Main application entry point
├── dependencies.py # Auth dependency (Session Check + RBAC)
├── routes/
│ └── auth.py # Auth endpoints (Login/Logout/Session)
├── static/
│ ├── firebase-auth.js # Client-side auth logic
│ └── style.css # Google Branding styles
├── templates/
│ └── base.html # Base template with Auth integration
├── config/ # [GIT IGNORED] Local config & keys
│ ├── firebaseConfig # JS Object with Firebase Keys
│ └── service-account.json # GCP Service Account Key
├── run_dev.py # Dev Runner (Auto-injects config)
└── seed_firestore.py # Helper to create RBAC rules
Before running the code, you must configure your Google Cloud & Firebase project:
- Create a Project: Go to console.firebase.google.com.
- Enable Auth:
- Navigate to Authentication > Sign-in method.
- Enable Google as a provider.
- Enable Firestore:
- Navigate to Firestore Database.
- Create database (start in Production mode or Test mode).
- Get Credentials:
- Frontend Config: Go to Project Settings > General > Your apps > Add Web App (</> icon). Copy the
firebaseConfigobject. - Backend Key: Go to Project Settings > Service accounts. Click Generate new private key. Save this JSON file.
- Frontend Config: Go to Project Settings > General > Your apps > Add Web App (</> icon). Copy the
- Create Config Directory:
mkdir config
- Add Frontend Config:
Create a file
config/firebaseConfigand paste your JS config object:const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_PROJECT.firebaseapp.com", projectId: "YOUR_PROJECT", // ... };
- Add Backend Key:
Place your downloaded Service Account JSON file inside the
config/directory (e.g.,config/service-account.json).
pip install -r requirements.txtBefore running, you must create an Access Rule (RBAC) so you can log in. We've included a script to do this for you:
python seed_firestore.py
# Follow the prompt to enter your email.This creates a document in the auth_environments collection (specifically the dev document) mapping your email to the admin role.
Use the included runner script to automatically inject your config/ keys as environment variables:
python run_dev.pyOpen http://localhost:8000.
- Copy
dependencies.pyandroutes/auth.pyto your new project. - Copy
static/andtemplates/assets. - Include the router in your main
app.py:from routes import auth app.include_router(auth.router)
- Protect routes using the dependency:
from dependencies import get_current_user @app.get("/protected", dependencies=[Depends(get_current_user)]) def protected_route(): return {"data": "Secret"}
This addon is optimized for Google Cloud Run. We have included a Dockerfile for immediate deployment.
We have included a helper script that parses your local config/firebaseConfig and automatically builds the gcloud run deploy command with all necessary environment variables.
python deploy_cloud_run.pyFollow the interactive prompts to set your service name and region.
If you prefer to deploy manually, here is the equivalent command:
gcloud run deploy my-auth-service \
--source . \
# ... (rest of manual command if needed, or just omit if script covers it)Cloud Run uses the Default Compute Service Account by default. Ensure this account has the following IAM roles in your GCP project so it can verify tokens and check RBAC:
- Firebase Admin SDK Administrator Service Agent (or custom role with
firebaseauth.users.get,firebaseauth.users.createSessionCookie) - Cloud Datastore User (to read
auth_environmentsFirestore collection)
Note: You do NOT need to set GOOGLE_APPLICATION_CREDENTIALS in Cloud Run. The library automatically finds the metadata server credentials.
| Variable | Description | Default |
|---|---|---|
AUTH_ENVIRONMENT |
The Firestore document ID to check for allowed users. | production |
GOOGLE_APPLICATION_CREDENTIALS |
Path to Service Account JSON. Auto-set by run_dev.py. |
Local Only |
- Login: Successfully redirected to Google and back. Page says "Signed in as...".
- Session Persistence: Refresh the page. You should remain logged in (session cookie is working).
- RBAC Enforcement:
- Try to login with an email not in your
devdocument. You should get a 403 Forbidden. - Try to access
/dashboard. It should work only if you are in the allowed list.
- Try to login with an email not in your
- Logout: Click "Sign Out". The session cookie is cleared and you are redirected.

