Building a production-grade authentication and authorization system in FastAPI – Day 1

|

I’m kicking off my first major coding project: building a master authentication and authorization system in FastAPI.

What I’m Building

The goal is a reusable, modular skeleton that supports:

  • Authentication
    • Email + password
    • Phone number login
    • Social logins (Google, LinkedIn, GitHub, Facebook, Microsoft, etc.)
    • Passwordless options (magic links, future WebAuthn integration)
  • Authorization
    • Global roles (super admin, manager, internal team, jobseeker, etc.)
    • Organization-level roles (company admins can invite team members and assign roles)
    • User-defined custom roles and permissions
    • Scalable role-permission mapping (RBAC with flexibility)
  • Transport & Security
    • JWT-based access and refresh tokens
    • HttpOnly secure cookies for transport
    • Short-lived access tokens + rotating refresh tokens
    • Room for future enhancements (Redis cache, rate limiting, audit logs, etc.)

Basically: a one-time master solution for authentication & authorization. Once the skeleton is built, I’ll be able to cut, configure, and reuse it across projects without reinventing the wheel.

Why I’m Making This

As a digital marketer who codes on the side, I’m constantly dreaming up ideas for small tools and apps. The problem? Every idea eventually hits the same wall: auth.

Authentication and authorization are tricky, security-sensitive, and too easy to get wrong. I found myself going in circles — trying different approaches, reading endless docs, and still not having the confidence to ship something production-ready.

So instead of hacking together solutions each time, I decided to invest once in building a master-level auth skeleton. This way:

  • I deepen my understanding of Python, FastAPI, and security.
  • I always have a reusable codebase for any future project.
  • I document everything here, so others can learn along with me.

Tools & Plugins

I’ll be working with:

  • FastAPI – for the backend framework
  • SQLAlchemy + Alembic – for database models & migrations
  • PyJWT – for token handling
  • Passlib – for password hashing
  • httpx / authlib – for OAuth2 integrations (Google, GitHub, etc.)
  • Pydantic – for validation
  • Redis (future) – for caching, token blacklisting, and rate limiting

Folder Structure

fastapi_auth_system/

├── app/
│ ├── core/
│ │ ├── config.py # settings/env
│ │ ├── security.py # JWT, password hashing
│ │ ├── deps.py # common dependencies (get_current_user)
│ │ └── utils.py # helpers
│ │
│ ├── auth/
│ │ ├── models.py # User, OAuthAccount, RefreshToken
│ │ ├── providers/
│ │ │ ├── google.py
│ │ │ ├── github.py
│ │ │ ├── linkedin.py
│ │ │ ├── microsoft.py
│ │ │ ├── facebook.py
│ │ │ ├── email_password.py
│ │ │ └── phone.py
│ │ ├── routes.py # include enabled providers
│ │ └── service.py # login, signup, refresh
│ │
│ ├── orgs/
│ │ ├── models.py # Organization, Membership, Role, Permission
│ │ ├── routes.py # Org CRUD, invite, assign roles
│ │ └── service.py # Org logic
│ │
│ ├── main.py # FastAPI app, router includes
│ └── db.py # SQLAlchemy session

├── migrations/ # Alembic migrations
├── .env.example # sample env vars
├── requirements.txt
└── README.md

📅 Project Roadmap (Daily ~1h Sessions)

Week 1: Foundations

  1. Day 1 – Project setup
    • Create FastAPI project structure
    • Setup core/ (config, db, utils)
    • Setup Alembic migrations
  2. Day 2 – User model & base tables
    • Build users table (id, email, password, etc.)
    • Setup hashing & password management
    • Test with one endpoint (POST /signup)
  3. Day 3 – JWT token system
    • Implement access + refresh token generation
    • Add cookie-based transport (Set-Cookie: HttpOnly)
    • Secure GET /me route
  4. Day 4 – Modular social login providers (Google example)
    • Create auth/providers/google.py
    • Handle OAuth2 callback, link to user account
  5. Day 5 – Config-driven providers
    • Add .env toggles for Google, GitHub, etc.
    • Test enabling/disabling providers

Week 2: Authorization Layer

  1. Day 6 – Roles & permissions models
    • Add Role, Permission, Membership tables
    • Create seeding for global roles
  2. Day 7 – Global authorization
    • Implement dependency require_global_role("super_admin")
    • Protect some routes
  3. Day 8 – Org-level authorization
    • Add org creation & membership invites
    • Implement require_permission("post_job", org_id)
  4. Day 9 – Policy engine integration
    • Abstract permissions checking logic
    • Plug in a rules engine (e.g., Casbin)
  5. Day 10 – User-defined roles
    • Add API for creating custom roles in an org
    • Attach permissions dynamically

Week 3: Scalability Hooks

  1. Day 11 – Cache adapters
    • Add CacheBackend interface
    • Implement InMemoryCache & RedisCache
  2. Day 12 – Token blacklist & refresh rotation
    • Store refresh tokens in Redis/DB
    • Implement logout & revoke flow
  3. Day 13 – Rate limiting hooks
    • Add dependency wrapper for request limiting
    • Default = no-op, enable with Redis
  4. Day 14 – Audit logging hooks
    • Add event publishing (UserLoggedIn, RoleChanged)
    • Default = log file, later can be Kafka
  5. Day 15 – Testing & CI
    • Setup pytest
    • Basic integration tests (signup, login, role check)

Week 4: Advanced & Hardening

  1. Day 16 – Multi-tenancy strategy
    • Org scoping across DB queries
    • Support both global + org roles in same flow
  2. Day 17 – WebAuthn / passwordless setup
    • Add skeleton for passkey login
    • Fallback to email+password
  3. Day 18 – Security hardening
    • CSRF protection for cookies
    • Secure headers (HSTS, CORS)
  4. Day 19 – Deployment ready
    • Dockerfile
    • Gunicorn + Uvicorn workers
    • .env templates
  5. Day 20 – Final review & template packaging
    • Document how to enable/disable providers
    • Prepare cookiecutter template repo

The Goal

By the end, I’ll have:

  • A production-ready FastAPI auth system
  • A documented learning path for myself and others
  • A reusable skeleton I can cut and adapt for future apps

This is the starting point of my Python journey — and the foundation for many side projects to come.

Tomorrow, I’ll dive into Day 1: project setup & base configs.

Leave a Reply