A standalone, reusable authentication microservice built with FastAPI, SQLAlchemy, and JWT Bearer tokens.
- User Registration:
POST /api/v1/auth/signup - Login:
POST /api/v1/auth/login(Returns JWT Bearer Token) - Token Refresh:
POST /api/v1/auth/refresh(Sliding session) - Profile Management: Get, update, and delete user profiles.
- Password Management: Change and reset passwords.
- Database Agnostic: Supports SQLite (default) and PostgreSQL.
- Security: Includes Rate Limiting, Clickjacking protection, XSS protection, and Trusted Host middleware.
- Observability: Structured JSON logging and Request ID tracking for easier debugging and monitoring.
- Python 3.12+
- Poetry (Dependency Manager)
-
Install Dependencies:
poetry install
-
Environment Configuration: Copy
.env.exampleto.envand update secrets:cp .env.example .env
-
Run Locally:
poetry run uvicorn app.main:app --reload
Access Swagger UI at http://localhost:8000/docs.
-
Build the Image:
docker build -t auth-service . -
Run the Container:
docker run -d -p 8000:8000 --name auth-service --env-file .env auth-service
Access at
http://localhost:8000.
- Trusted Host Middleware: By default,
ALLOWED_HOSTSis set to["*"]to allow easy local development. For production, you must update this list inapp/main.pyto include only your allowed domains (e.g.,["example.com", "*.example.com"]) to prevent Host Header attacks.
To verify that the application is running correctly and security headers are active:
curl -I http://localhost:8000/api/healthExpected output includes security headers and a unique Request ID:
HTTP/1.1 200 OK
x-frame-options: DENY
x-content-type-options: nosniff
x-request-id: <unique-uuid>
...- Swagger UI:
/docs- Interactive API documentation and testing. - ReDoc:
/redoc- Alternative API documentation.
To use this service in your other applications (Web/Mobile):
- Login: Send credentials to
/api/v1/auth/login. - Store Token: Save the
access_tokensecurely (e.g.,SecureStoreon iOS,EncryptedSharedPreferenceson Android,HttpOnly Cookieon Web). - Authenticate Requests: Add header
Authorization: Bearer <your_token>to requests requiring auth. - Handle 401 Unauthorized: If a request fails with 401, try traversing to the login screen or using the
/refreshendpoint if the session is still valid.
Based on the current implementation, the following enhancements are recommended to make the service production-ready and secure.
- Email Verification: Implement SMTP integration to send verification codes/links upon signup. Ensure users verify their email before logging in.
- True Refresh Tokens: Switch to a dual-token system:
- Access Token: Short-lived (e.g., 15-30 mins).
- Refresh Token: Long-lived (e.g., 7-30 days), stored securely in the database.
- Redis Integration:
- Token Revocation (Logout): Implement a "Blocklist" pattern using Redis to invalidate tokens instantly upon logout.
- Rate Limiting: Use Redis to protect
/loginand/signupendpoints from brute-force attacks.
- Create a reusable dependency (e.g.,
RequiresRole("admin")) to protect endpoints based on theRolemodel. - Seed default permissions and roles automatically on startup.
- Metrics: Add an endpoint (
/metrics) exposing Prometheus-compatible metrics (latency, error rates).
- Integration Tests: Add tests using a real database (Dockerized Postgres) in CI to catch SQL dialect issues.
- Load Testing: Use Locust or K6 to benchmark authentication throughput.