A secure, production-ready authentication server built with FastAPI, SQLAlchemy, and JWT. Provides user registration, login, and protected route access using OAuth2 Password Flow with Bearer tokens.
- ✅ Secure password hashing using bcrypt
- ✅ JWT-based authentication with configurable token expiration
- ✅ HTTP Bearer token security via
HTTPBearer - ✅ Database-backed user storage with SQLAlchemy ORM
- ✅ Automatic session validation on protected endpoints
- ✅ Standardized error responses with HTTP status codes
- ✅ Type-safe with full Python type hints
- Client sends
POST /loginwithusernameandpassword - Server verifies credentials against database
- If valid, server issues a signed JWT access token
- Client includes token in
Authorization: Bearer <token>header for protected requests - Server validates token signature and extracts user ID to authorize access
- Python 3.8+
- PostgreSQL / MySQL / SQLite (configured in
database.py) pip install fastapi uvicorn python-dotenv passlib[bcrypt] python-jose[cryptography] sqlalchemy
- Replace
SECRET_KEYin your environment (never commit to version control):
export SECRET_KEY="your-super-secret-key-here"auth-server/
├── auth.py
├── database.py
├── models.py
├── main.py
└── requirements.txt
Create a Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "auth:app", "--host", "0.0.0.0", "--port", "8000"]Build and run:
docker build -t auth-server . docker run -p 8000:8000 -e SECRET_KEY="your-production-key" auth-server
Environment Variables (Production) Use .env file or environment variables:
SECRET_KEY=your_very_long_random_secret_key_here DATABASE_URL=postgresql://user:pass@localhost/dbname
Use python-dotenv to load .env automatically in main.py.
🤝 Contributing Contributions are welcome! Whether you're fixing bugs, improving documentation, or adding new features like refresh tokens or email verification — please open an issue or PR.
See CONTRIBUTING.md for guidelines.
📄 License This project is licensed under the MIT License — see LICENSE for details.


