Skip to content

Repository files navigation

FastAPI Firebase RBAC

Python FastAPI Firebase

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.

Architecture

This addon is designed as an Embedded Library, not a separate microservice/proxy. It lives inside your FastAPI application.

GCP Auth Architecture

UI Preview

Deployed App Screenshot

Features

  • 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_ENVIRONMENT variable.
  • Drop-In Ready: Modular dependencies.py and routes/auth.py can 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.

Why use this? (Comparison)

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.

Project Structure

.
├── 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

Setup & Installation

1. Firebase Prerequisites

Before running the code, you must configure your Google Cloud & Firebase project:

  1. Create a Project: Go to console.firebase.google.com.
  2. Enable Auth:
    • Navigate to Authentication > Sign-in method.
    • Enable Google as a provider.
  3. Enable Firestore:
    • Navigate to Firestore Database.
    • Create database (start in Production mode or Test mode).
  4. Get Credentials:
    • Frontend Config: Go to Project Settings > General > Your apps > Add Web App (</> icon). Copy the firebaseConfig object.
    • Backend Key: Go to Project Settings > Service accounts. Click Generate new private key. Save this JSON file.

2. Local Configuration

  1. Create Config Directory:
    mkdir config
  2. Add Frontend Config: Create a file config/firebaseConfig and paste your JS config object:
    const firebaseConfig = {
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_PROJECT.firebaseapp.com",
        projectId: "YOUR_PROJECT",
        // ...
    };
  3. Add Backend Key: Place your downloaded Service Account JSON file inside the config/ directory (e.g., config/service-account.json).

3. Installation

pip install -r requirements.txt

4. Seed the Database

Before 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.

Usage

Running Locally

Use the included runner script to automatically inject your config/ keys as environment variables:

python run_dev.py

Open http://localhost:8000.

Integrating into New Projects

  1. Copy dependencies.py and routes/auth.py to your new project.
  2. Copy static/ and templates/ assets.
  3. Include the router in your main app.py:
    from routes import auth
    app.include_router(auth.router)
  4. 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"}

Deploying to Cloud Run

This addon is optimized for Google Cloud Run. We have included a Dockerfile for immediate deployment.

1. Build & Deploy (Automated)

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.py

Follow the interactive prompts to set your service name and region.

2. Manual Deployment (Optional)

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)

2. Service Account Permissions

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_environments Firestore collection)

Note: You do NOT need to set GOOGLE_APPLICATION_CREDENTIALS in Cloud Run. The library automatically finds the metadata server credentials.

Environment Variables

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

Verification Checklist

  • 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 dev document. You should get a 403 Forbidden.
    • Try to access /dashboard. It should work only if you are in the allowed list.
  • Logout: Click "Sign Out". The session cookie is cleared and you are redirected.

About

Universal FastAPI Auth Module for GCP. Drop-in RBAC via Firebase & Firestore. A portable application-layer alternative to Google Cloud Identity-Aware Proxy (IAP) for securing apps across Localhost and Cloud Run.

Resources

Stars

Watchers

Forks

Contributors

Languages