A production-grade authentication gateway built with FastAPI that provides centralized Single Sign-On (SSO) across multiple applications and subdomains.
The gateway acts as an Identity Provider (IdP), allowing external services and client applications to authenticate users through a unified authentication system. It supports secure JWT-based authentication, refresh token rotation, cross-subdomain session management, and role-based access control.
Typical client applications include:
- Django / DRF applications
- FastAPI services
- React / Next.js frontends
- Internal admin panels
- Microservices architectures
Authenticate users once and share authenticated sessions across multiple services and subdomains.
Example:
admin.example.comstaff.example.comdashboard.example.com
The gateway functions as an authentication provider for external applications.
Client applications can:
- Redirect users to the SSO provider
- Validate JWT access tokens
- Refresh sessions securely
- Retrieve public signing keys via JWKS
Uses asymmetric cryptography with RS256 public/private key signing.
Benefits:
- Stateless access token validation
- Secure inter-service authentication
- Public key verification without exposing private keys
Implements secure refresh token rotation:
- Long-lived refresh tokens
- SHA-256 hashed storage
- Automatic rotation
- Revocation support
- Replay attack mitigation
Authentication tokens are stored in secure HttpOnly cookies.
Cookie configuration:
HttpOnlySecureSameSite=NoneDomain=.yourdomain.com
Supports seamless authentication across subdomains.
Users can be redirected automatically based on roles.
Example:
admin→admin.example.comstaff→staff.example.com
Secure logout flow:
- Refresh token revocation
- Session invalidation
- Cookie cleanup
Exposes public signing keys through a JWKS endpoint for external service verification.
Useful for:
- Microservices
- API gateways
- Third-party integrations
- Distributed architectures
Optional CSRF protection for state-changing requests.
Protects authentication endpoints against:
- Brute-force attacks
- Credential stuffing
- Abuse attempts
Includes:
- HTTPS enforcement
- HSTS headers
- Secure cookie policies
- Audit logging
- Secret-based key management
- Reverse proxy support via Nginx
┌────────────────────┐
│ Client App │
│ (DRF / React) │
└─────────┬──────────┘
│
│ Redirect/Login
▼
┌────────────────────┐
│ SSO Gateway │
│ FastAPI IdP │
└─────────┬──────────┘
│
┌───────────────────┴───────────────────┐
│ │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ PostgreSQL │ │ Redis │
│ Users & Tokens │ │ Revocation Cache │
└──────────────────┘ └──────────────────┘
| Component | Technology |
|---|---|
| API Framework | FastAPI |
| Database | PostgreSQL |
| Cache / Revocation | Redis |
| ORM | SQLAlchemy |
| JWT Library | python-jose |
| Reverse Proxy | Nginx |
| Migrations | Alembic |
root project (idp)/
│
├── app/
│ ├── main.py
│ ├── models.py
│ ├── models.py
│ ├── core/
│ │ ├── authentication.py
│ │ ├── config.py
│ │ └── databae.py
│ │
│ ├── keys/
│ │ ├── private.pem
│ │ └── public.pem
│ │
│ ├── routers/
│ │ ├── auth.py
│ │ └── core.py
│ │
│ ├── tasks/
│ │ ├── celery.py
│ │ ├── redis.py
│ │ └── tass.py
│ │
│ ├── templates/
│ │ └── login.html
│ │
│ └── utils/
│ └── ......
│
├── migrations/
├── requirements.txt
├── .env.example
├── docker-compose.yml
└── README.md
# JWT Configuration
JWT_PRIVATE_KEY_PATH=/run/secrets/jwt_private.pem
JWT_PUBLIC_KEY_PATH=/run/secrets/jwt_public.pem
JWT_ALGORITHM=RS256
# Token Expiration
ACCESS_TOKEN_EXPIRE_MINUTES=15
REFRESH_TOKEN_EXPIRE_DAYS=30
# Cookie Configuration
COOKIE_DOMAIN=.yourdomain.com
COOKIE_SECURE=true
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/sso_db
# Redis
REDIS_URL=redis://localhost:6379/0Client application redirects the user to the SSO provider.
POST /api/auth/loginThe gateway:
- Validates credentials
- Determines user roles
- Issues access & refresh tokens
- Stores tokens in secure cookies
- Returns redirect target
The browser automatically sends authentication cookies with requests.
Protected services:
- Validate JWT access tokens
- Verify token signatures using JWKS
- Extract user claims and roles
POST /api/auth/refreshWhen the access token expires:
- Refresh token is validated
- Old refresh token is revoked
- New token pair is generated
- Cookies are updated
POST /api/auth/logoutThe logout process:
- Revokes refresh tokens
- Invalidates sessions
- Clears authentication cookies
A Django REST Framework application can use the gateway as its authentication provider.
User → DRF App → Redirect to SSO Gateway
↓
User Authenticated
↓
JWT Tokens Issued by FastAPI IdP
↓
DRF Validates Access Token
↓
User Logged In
Example DRF middleware/authentication integration:
from jose import jwt
from django.conf import settings
def verify_access_token(token: str):
payload = jwt.decode(
token,
settings.SSO_PUBLIC_KEY,
algorithms=["RS256"]
)
return payloadgit clone https://github.com/your-org/sso-auth-gateway.git
cd sso-auth-gatewaypython -m venv .venv
source .venv/bin/activateWindows:
.venv\Scripts\activatepip install -r requirements.txtalembic upgrade headuvicorn app.main:app --reload| Security Feature | Status |
|---|---|
| HTTPS Enforcement | ✅ |
| HSTS Headers | ✅ |
| HttpOnly Cookies | ✅ |
| Secure Cookies | ✅ |
| SameSite=None Cookies | ✅ |
| Refresh Token Rotation | ✅ |
| Refresh Token Revocation | ✅ |
| RS256 JWT Signing | ✅ |
| Rate Limiting | ✅ |
| CSRF Protection | ✅ |
| Audit Logging | ✅ |
| Secret-Based Key Storage | ✅ |
Production deployment recommendation:
- FastAPI application
- PostgreSQL database
- Redis revocation cache
- Nginx reverse proxy
- Dockerized infrastructure
- TLS termination at Nginx
- Enterprise SSO systems
- Internal company platforms
- Multi-tenant SaaS applications
- Microservices authentication
- Cross-subdomain authentication
- Centralized authentication provider
- API gateway authentication
MIT License
