{"id":21457821,"url":"https://github.com/echo298327/auth-gateway-fastapi-keycloak","last_synced_at":"2026-04-11T04:32:50.239Z","repository":{"id":262844657,"uuid":"888535160","full_name":"Echo298327/auth-gateway-fastapi-keycloak","owner":"Echo298327","description":"Starter template for building scalable FastAPI microservices with Docker Compose and Keycloak for authentication.","archived":false,"fork":false,"pushed_at":"2024-12-28T17:16:07.000Z","size":151,"stargazers_count":1,"open_issues_count":4,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-23T13:33:55.678Z","etag":null,"topics":["api-gateway","authentication","docker-compose","fastapi","keycloak","microservices","mongodb"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Echo298327.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-14T15:07:50.000Z","updated_at":"2025-01-17T09:20:22.000Z","dependencies_parsed_at":"2024-11-14T16:25:33.626Z","dependency_job_id":"2f126464-9a23-460f-a83a-836d043e0892","html_url":"https://github.com/Echo298327/auth-gateway-fastapi-keycloak","commit_stats":null,"previous_names":["echo298327/auth-gateway-fastapi-keycloak"],"tags_count":0,"template":true,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Echo298327%2Fauth-gateway-fastapi-keycloak","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Echo298327%2Fauth-gateway-fastapi-keycloak/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Echo298327%2Fauth-gateway-fastapi-keycloak/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Echo298327%2Fauth-gateway-fastapi-keycloak/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Echo298327","download_url":"https://codeload.github.com/Echo298327/auth-gateway-fastapi-keycloak/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243971193,"owners_count":20376784,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-gateway","authentication","docker-compose","fastapi","keycloak","microservices","mongodb"],"created_at":"2024-11-23T06:07:14.036Z","updated_at":"2026-04-11T04:32:50.218Z","avatar_url":"https://github.com/Echo298327.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Auth Gateway — IAM, Authentication \u0026 Authorization\n\nA complete **IAM (Identity \u0026 Access Management)** solution with **Keycloak**. Provides authentication, authorization, user management, role-based access control, and an API gateway — ready to plug into any project.\n\n## What's Included\n\n- **Gateway Service** — routes all API requests, validates JWT tokens, checks permissions via Keycloak\n- **IAM Service** — user management (CRUD), role assignment, Keycloak initialization\n- **Keycloak** — authentication, token issuing, role-based permission evaluation\n- **MongoDB** — stores users, service versions\n- **PostgreSQL** — Keycloak's database\n- **PgAdmin** — PostgreSQL admin UI\n- **auth-gateway-serverkit** — shared library for auth middleware, Keycloak API, request handling\n- **MFA / 2FA** — optional TOTP-based multi-factor authentication via a custom Keycloak extension\n- **Security Headers** — X-Content-Type-Options, CSP, HSTS, Referrer-Policy, Permissions-Policy\n- **Configurable RBAC** — define roles, policies, and per-endpoint permissions in JSON files\n- **CI/CD Pipeline** — linting, security scanning, and tests on pull requests\n\n## Documentation\n\n- [Workflow Guide](docs/WORKFLOW_GUIDE.md) — step-by-step: login, create users, manage roles, add new services\n- [API Documentation](docs/API.md) — all endpoint references\n- [Authorization Guide](docs/AUTHORIZATION_GUIDE.md) — how roles, policies, and permissions work; how to add new roles/endpoints/services\n- [Serverkit \u0026 Initializer Guide](docs/SERVERKIT_GUIDE.md) — how the Keycloak initializer works, customizing the serverkit\n- [Postman Collection](postman_collection.json) — import into Postman to test all endpoints\n\n---\n\n## Getting Started\n\n### Prerequisites\n\n- [Docker](https://www.docker.com/get-started) and [Docker Compose](https://docs.docker.com/compose/install/)\n- [Python 3.12+](https://www.python.org/)\n- [MongoDB](https://www.mongodb.com/) (running locally or cloud-hosted)\n\n### Installation\n\n1. Clone the repository:\n\n   ```bash\n   git clone https://github.com/Echo298327/auth-gateway-fastapi-keycloak.git\n   cd auth-gateway-fastapi-keycloak\n   ```\n\n2. Configure environment variables:\n\n   ```bash\n   cp .env.docker.example .env.docker\n   cp .env.example .env\n   ```\n\n   The `.example` files come pre-configured with default dev values that work out of the box. Change passwords/secrets as needed for your environment.\n\n   - `.env.docker` — used by Docker Compose (not committed to git)\n   - `.env` — used for local development without Docker\n\n3. Start all services:\n\n   ```bash\n   docker compose up --build -d\n   ```\n\n4. Access the services:\n\n   | Service | URL |\n   |---------|-----|\n   | Gateway | http://localhost:8080 |\n   | IAM | http://localhost:8081 |\n   | Keycloak Admin Console | http://localhost:9000 |\n   | PgAdmin | http://localhost:5050 |\n\n### First Login\n\nA system admin account is created automatically on first startup.\n\n```\nPOST http://localhost:8080/api/login\nBody: {\n  \"username\": \"sysadmin\",\n  \"password\": \"\u003cSYSTEM_ADMIN_PASSWORD from .env.docker\u003e\"\n}\n```\n\nThe response contains `access_token`, `refresh_token`, and user data. Use the access token in the `Authorization: Bearer \u003ctoken\u003e` header for all subsequent requests.\n\n\u003e **Note:** If the user has MFA enabled, an optional `\"totp\"` field is required. See the [MFA section](#mfa--two-factor-authentication) for the full flow.\n\n### Postman\n\n1. Import `postman_collection.json` into Postman\n2. Run the Login request\n3. The token is automatically saved to the environment\n4. All other requests use it automatically\n\n---\n\n## Project Structure\n\n```\nauth-gateway-fastapi-keycloak/\n|\n|-- .env.example                      # Local dev environment template\n|-- .env.docker.example               # Docker environment template\n|-- docker-compose.yml                # All services orchestration\n|-- postman_collection.json           # Postman collection\n|\n|-- docs/                             # Documentation\n|   |-- API.md                        # API endpoint reference\n|   |-- AUTHORIZATION_GUIDE.md        # Role \u0026 permission guide\n|   |-- WORKFLOW_GUIDE.md             # Usage workflow guide\n|   |-- SERVERKIT_GUIDE.md            # Serverkit \u0026 initializer guide\n|\n|-- deployment/\n|   |-- docker/\n|   |   |-- gateway.Dockerfile\n|   |   |-- iam.Dockerfile\n|   |   |-- keycloak.Dockerfile\n|   |   |-- keycloak.conf\n|   |-- pgadmin_server.json\n|\n|-- shared/                           # Shared utilities across services\n|   |-- logging/\n|       |-- log_header.py\n|\n|-- gateway/                          # Gateway Service\n|   |-- requirements.txt\n|   |-- src/\n|       |-- main.py\n|       |-- api/routes/\n|       |   |-- gateway.py            # Routes: login, refresh, logout, proxy\n|       |-- core/\n|       |   |-- config.py             # Service map, app settings\n|       |-- schemas/\n|       |   |-- gateway.py            # Login, Refresh request models\n|       |-- middleware/\n|       |   |-- security_headers.py   # Security headers middleware\n|       |-- services/\n|       |   |-- proxy.py              # Request forwarding, access control\n|       |   |-- auth.py               # Login, refresh, logout handlers\n|       |   |-- mfa.py                # MFA helpers: enroll, verify, Keycloak calls\n|\n|-- iam/                              # IAM Service (Identity \u0026 Access Management)\n|   |-- requirements.txt\n|   |-- src/\n|       |-- main.py                   # Startup: DB init, Keycloak init, admin creation\n|       |-- api/routes/\n|       |   |-- user.py               # User CRUD endpoints\n|       |-- authorization/            # Role \u0026 permission config (JSON)\n|       |   |-- roles.json            # Realm roles + policies\n|       |   |-- services/\n|       |       |-- iam.json          # Resources + permissions for IAM\n|       |-- core/\n|       |   |-- config.py             # DB, Keycloak, app settings\n|       |-- domains/\n|       |   |-- users/                # User domain\n|       |   |   |-- models/user.py    # Beanie document model\n|       |   |   |-- schemas/user.py   # Pydantic schemas + AllowedRoles\n|       |   |   |-- services/user_manager.py\n|       |   |   |-- db/mongo/user.py  # DB operations\n|       |   |-- service_versions/     # Config version tracking\n|       |   |   |-- models/service_version.py\n|       |   |   |-- db/mongo/service_version.py\n|       |   |-- organizations/        # Placeholder for future domain\n|       |   |-- licenses/             # Placeholder for future domain\n|       |-- utils/\n|       |    |-- admin.py              # System admin helpers\n|       |    |-- roles.py              # Role validation\n|       |    |-- validation.py         # Input validation\n|       |    |-- exception_handler.py\n|       |-- keycloak_extensions/      # Custom Keycloak SPI extensions\n|       |    |-- mfa-provider/         # TOTP/2FA REST API (Java/Maven)\n|       |       |-- pom.xml\n|       |       |-- src/main/java/com/authgateway/keycloak/mfa/\n|       |       |-- target/mfa-provider-1.0.0.jar\n```\n\n---\n\n## Services\n\n| Service | Port | Description |\n|---------|------|-------------|\n| Gateway | 8080 | API gateway, JWT validation, permission checks, request routing |\n| IAM | 8081 | User management, Keycloak initialization, role management |\n| Keycloak | 9000 | Identity provider, token issuer, authorization server |\n| PostgreSQL | 5432 | Keycloak database |\n| PgAdmin | 5050 | PostgreSQL admin interface |\n\n---\n\n## Role System\n\nThree default roles: `user`, `admin`, `systemAdmin`.\n\n- Users can have **multiple roles** at the same time\n- Roles are assigned when creating a user and can be changed via update\n- `systemAdmin` is created automatically and cannot be assigned through the API\n- Roles, policies, and permissions are defined in JSON files under `iam/src/authorization/`\n\nFor full details on how to add roles, restrict endpoints, and add new services, see the [Authorization Guide](docs/AUTHORIZATION_GUIDE.md).\n\n---\n\n## MFA / Two-Factor Authentication\n\nThe project includes optional TOTP-based 2FA powered by a custom Keycloak SPI extension (`iam/src/keycloak_extensions/mfa-provider/`).\n\n### How It Works\n\n1. **Enable MFA for a user** — set `\"enable_mfa\": true` when creating a user via `POST /api/user/create`. This sets the Keycloak `CONFIGURE_TOTP` required action.\n2. **First login** — user logs in with username + password. The gateway detects the required action and returns a QR code.\n3. **Scan \u0026 verify** — user scans the QR code with an authenticator app (Google Authenticator, Authy, etc.), then sends the OTP code. The gateway verifies it and completes setup.\n4. **Subsequent logins** — user sends `username`, `password`, and `totp` in the login request. Keycloak validates all three.\n\n### Login Response States\n\n| `mfa_action` | Meaning | Frontend should... |\n|---|---|---|\n| `\"setup\"` | First-time MFA setup | Show QR code, ask for OTP |\n| `\"setup_complete\"` | OTP verified, setup done | Ask user to login again with a fresh OTP |\n| `\"verify\"` | User has MFA, needs OTP | Show OTP input |\n\n### Building the MFA Extension\n\nThe Keycloak extension is a Java JAR built with Maven. It is automatically included in the Keycloak Docker image via the Dockerfile.\n\n```bash\ncd iam/src/keycloak_extensions/mfa-provider\nmvn clean package -DskipTests\n```\n\nFor full MFA extension documentation see [mfa-provider/README.md](iam/src/keycloak_extensions/mfa-provider/README.md).\n\n---\n\n## Keycloak Config Versioning\n\nThe IAM service tracks a `KEYCLOAK_CONFIG_VERSION` in code. On startup it compares with the version stored in MongoDB:\n\n- **Different**: runs full Keycloak sync (delete + recreate roles, policies, resources, permissions)\n- **Same**: skips, only verifies connection\n\nBump the version in `iam/src/core/config.py` whenever you change `roles.json` or any file in `authorization/services/`.\n\n---\n\n## Keycloak Admin Console\n\nFor advanced management you can access Keycloak directly:\n\n- **URL**: http://localhost:9000\n- **Username**: `admin` (from `KC_BOOTSTRAP_ADMIN_USERNAME`)\n- **Password**: from `KC_BOOTSTRAP_ADMIN_PASSWORD` in `.env.docker`\n\n---\n\n## CI/CD Pipeline\n\nRuns automatically on pull requests to `main`:\n\n| Check | Description |\n|-------|-------------|\n| Lint | Flake8 (unused imports, variables) |\n| Security (Dependencies) | Trivy vulnerability scan |\n| Security (Docker) | Trivy Docker image scan |\n| Tests | pytest |\n\n---\n\n## Production Checklist\n\nBefore deploying to production, review the following:\n\n- [ ] Set `CORS_ORIGINS` to specific trusted domains (not `*`)\n- [ ] Set `ENVIRONMENT=production` to enable HSTS headers\n- [ ] Use a secrets manager (e.g. Docker Secrets, Vault, AWS Secrets Manager) instead of `.env` files for credentials\n- [ ] Place a reverse proxy (Nginx / Caddy) in front for HTTPS termination\n- [ ] Use managed databases (e.g. MongoDB Atlas, AWS RDS for PostgreSQL) instead of containerized ones\n- [ ] Remove or restrict `pgadmin` from the compose file\n- [ ] Set Keycloak `hostname` to your actual domain in `keycloak.conf`\n- [ ] Review and restrict Keycloak admin credentials (`KC_BOOTSTRAP_ADMIN_*`)\n- [ ] Ensure `.env` and `.env.docker` are never committed (already in `.gitignore`)\n\nThe Dockerfiles, health endpoints (`/health`, `/readyz`), and environment-based configuration are designed to be portable — they work with Docker Compose, Kubernetes, or any container orchestrator.\n\n---\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md).\n\n## License\n\n[MIT License](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fecho298327%2Fauth-gateway-fastapi-keycloak","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fecho298327%2Fauth-gateway-fastapi-keycloak","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fecho298327%2Fauth-gateway-fastapi-keycloak/lists"}