A production‑ready authentication & authorization microservice for an online cinema platform. Built with FastAPI, PostgreSQL, and Redis; features JWT (access/refresh), RBAC roles/permissions, TOTP MFA, OAuth (Yandex example), rate limiting (leaky bucket), and OpenTelemetry tracing exported to Jaeger. Containerized with Docker.
Why use this? It’s a clean, modern async stack (Python 3.12, SQLAlchemy 2.0, Pydantic v2) with observability, security hardening, and strong DX (pre-commit, mypy, Ruff, Bandit).
- Features
- Architecture
- Project Layout
- Getting Started
- API Overview
- Security & Rate Limiting
- Observability
- Testing & Quality
- Development
- Changelog
- License
- 🔐 JWT-based auth: access/refresh tokens, blacklist on logout.
- 👥 RBAC: roles, user-role mapping, permission checks, caching in Redis.
- 🔑 OAuth: Yandex provider example using
authlib(easily extensible). - 🔒 MFA: TOTP enable/verify flows.
- 🚦 Rate limiting: Redis leaky bucket with role-aware config per traffic type.
- 🧾 Login history: partitioned by date for scalable reads/writes.
- 📈 Tracing: OpenTelemetry → Jaeger (FastAPI, SQLAlchemy, Redis, HTTPX instrumented).
- 🧰 DX: pre-commit (Ruff, mypy, Bandit, detect-secrets), pytest, mypy settings.
- 🐳 Dockerized:
docker-composeships Postgres, Redis, Jaeger, and the app.
flowchart LR
A[Client / Frontend] -->|JWT / Cookies| B(FastAPI App)
subgraph Service
B --> C[AuthService]
C --> D[(PostgreSQL)]
C --> E[(Redis)]
B --> F[RateLimiter]
B --> G[OAuth Providers]
end
B --> H[[OpenTelemetry]]
H --> I[Jaeger UI]
- FastAPI app exposes
/api/v1routes for auth and RBAC. - PostgreSQL stores users, roles, user_role mappings, login history (partitioned).
- Redis caches permissions, stores token blacklist & rate-limiter buckets.
- OpenTelemetry exports traces to Jaeger (UI on
http://localhost:16686).
auth_service/
├─ app/
│ ├─ api/v1/routes/ # auth.py, roles.py
│ ├─ core/ # logging, tracing, security, oauth, deps
│ ├─ db/ # async session factory
│ ├─ models/ # SQLAlchemy models
│ ├─ schemas/ # Pydantic v2 schemas
│ ├─ services/ # AuthService, RoleService, MFA
│ ├─ utils/ # cache, rate limiter
│ ├─ main.py # FastAPI app factory & middlewares
│ └─ cli.py # CLI (create superuser)
├─ alembic/ # migrations (init + partitioning, social accounts)
├─ docker-compose.yml # app + postgres + redis + jaeger
├─ Dockerfile # multi-stage, non-root user
├─ requirements.txt # pinned deps
└─ tests/ # pytest (e.g., test_register.py)
- Docker & Docker Compose
- (Optional) Python 3.12 + virtualenv
Copy and edit the example environment file:
cp auth_service/.env.exm auth_service/.env
# Fill in DB creds, JWT secrets (>= 16 chars), Redis URL, session secret, OAuth keysKey variables (see app/settings.py for details):
DATABASE_URL(async) /TEST_DATABASE_URLJWT_SECRET_KEY,JWT_REFRESH_SECRET_KEY,JWT_ALGORITHMREDIS_URLSESSION_SECRET_KEYFRONTEND_URLYANDEX_CLIENT_ID,YANDEX_CLIENT_SECRET,YANDEX_CALLBACK_URL- Tracing:
JAEGER_ENDPOINT(defaults tohttp://jaeger:4318/v1/traces)
From the auth_service directory:
docker compose build auth-service
docker compose up -d db redis jaeger
docker compose up -d auth-service
docker compose ps
# App health endpoint:
curl http://localhost:8000/healthOn container start, the entrypoint runs
alembic upgrade headautomatically.
Initial migration (autogenerate) – if you need to (for local dev only):
docker compose run --rm --entrypoint bash auth-service -c "alembic -c /app/alembic.ini revision --autogenerate -m 'Create initial tables'"
docker compose down && docker compose up -dPartition login_history by login_at (range partitions):
docker compose run --rm --entrypoint bash auth-service -c "alembic -c /app/alembic.ini revision --autogenerate -m 'Partition login_history by login_at'"
# Edit the generated migration to add the DDL (see alembic/migration_create_login_history_partitions.py)
docker compose run --rm --entrypoint bash auth-service -c "alembic -c /app/alembic.ini upgrade head"
docker compose up -d auth-service# Interactive prompts for username/password
docker compose run --rm auth-service python -m app.cli create-superuser- Swagger UI:
http://localhost:8000/api/v1/docs - ReDoc:
http://localhost:8000/api/v1/redoc - OpenAPI:
http://localhost:8000/api/v1/openapi.json
/api/v1/auth
POST /register— create new user.POST /login— exchange credentials for access/refresh tokens.POST /refresh— rotate refresh → new access + refresh.POST /logout— invalidate the provided refresh token (blacklist).POST /logout_all_other_sessions— keep current session, invalidate the rest.GET /history— login history for current user.GET /{{provider}}/login— redirect to OAuth provider (e.g.,yandex).GET /{{provider}}/callback— OAuth callback → issue local tokens.
Example: Login
curl -X POST http://localhost:8000/api/v1/auth/login -H "Content-Type: application/json" -d '{"login":"demo","password":"secret"}'Use Authorization: Bearer <access_token> for protected routes.
/api/v1/roles
POST /— create role (name, permissions[]).GET /— list roles.GET /{{role_id}}— get role by id.PUT /{{role_id}}— update role.DELETE /{{role_id}}— delete role.POST /{{role_id}}/assign/{{user_id}}— assign role to user.DELETE /{{role_id}}/revoke/{{user_id}}— revoke role from user.GET /{{user_id}}/permissions— list effective permissions for user.
Permission checks use a cached set in Redis; superusers implicitly have
*(all).
- Passwords hashed with bcrypt via Passlib.
- JWTs signed with
HS256; refresh & access secrets are separate. - Refresh-token rotation with blacklist (Redis) on logout.
- Leaky bucket rate limiting in Redis with role-aware config per traffic type
(
default,login,register). Seeapp/settings.py → rate_limit_config.
- OpenTelemetry instrumentation for FastAPI, SQLAlchemy, Redis, HTTPX.
- Exporter → Jaeger (Collector OTLP HTTP enabled).
- Jaeger UI at http://localhost:16686.
# Run tests
pytest -q
# Type-check
mypy
# Lint & format
ruff check --fix
ruff format
# Pre-commit (recommended)
pre-commit install
pre-commit run --all-filesLocal (without Docker), e.g. for quick hacking:
python -m venv .venv && source .venv/bin/activate
pip install -r auth_service/requirements.txt
export $(grep -v '^#' auth_service/.env | xargs) # or use python-dotenv
uvicorn app.main:app --host 0.0.0.0 --port 8000See Changelog.md for notable changes (e.g., tracing, partitions, rate limiting).
No license specified. If you intend to open source this project, add a LICENSE file (e.g., MIT).
- FastAPI, SQLAlchemy, Pydantic
- OpenTelemetry & Jaeger
- Redis & PostgreSQL