A secure, scalable authentication REST API designed with modern backend engineering and security practices.
Auth API provides a complete identity and authentication backend for modern applications, including JWT authentication, refresh-token rotation, password security, email verification, password recovery, session management, and a clean layered architecture.
- 🔐 JWT-based authentication
- 🔄 Refresh-token rotation and revocation
- 🛡️ Argon2 password hashing
- 📧 Email verification and password recovery
- 👤 User and session management
- 🧱 Layered service-oriented architecture
- ⚡ Fully asynchronous database operations
- 🗄️ PostgreSQL + SQLAlchemy
- 🧪 Automated testing
- 🐳 Docker-ready deployment
- 📚 Automatic OpenAPI / Swagger documentation
- 🚦 Rate limiting and security middleware
- ⚙️ Environment-based configuration
Authentication is one of the most security-sensitive parts of an application.
Instead of embedding authentication logic directly inside route handlers, Auth API separates responsibilities into dedicated layers:
┌──────────────────────┐
│ HTTP Client │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Router Layer │
│ HTTP / Validation │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Service Layer │
│ Business Logic │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Repository Layer │
│ Data Operations │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ PostgreSQL DB │
└──────────────────────┘
This makes the system easier to:
- Test
- Maintain
- Extend
- Secure
- Scale
- Integrate into other applications
| Feature | Status |
|---|---|
| User registration | ✅ |
| Secure login | ✅ |
| JWT access tokens | ✅ |
| Refresh tokens | ✅ |
| Refresh-token rotation | ✅ |
| Token revocation | ✅ |
| Session logout | ✅ |
| Logout all sessions | ✅ |
| Protected routes | ✅ |
- User profile retrieval
- Profile updates
- Password changes
- Account management
- UUID-based user identities
- Session-aware authentication
Security is a first-class concern throughout the application.
- Argon2 password hashing
- JWT signing and validation
- Short-lived access tokens
- Refresh-token rotation
- Token revocation
- Password strength validation
- Request validation with Pydantic
- SQL injection protection through ORM/query parameterization
- CORS configuration
- Security headers
- Rate limiting
- Environment-based secrets
- Centralized exception handling
⚠️ Production deployments should additionally configure HTTPS, secure secret storage, trusted CORS origins, email infrastructure, monitoring, and appropriate reverse-proxy settings.
The authentication system supports:
- Email verification
- Verification tokens
- Password reset requests
- Password reset tokens
- Secure account recovery workflows
- Automatic Swagger documentation
- ReDoc documentation
- Async database support
- Dependency injection
- Repository pattern
- Service layer architecture
- Structured logging
- Custom exception handling
- Docker support
- Alembic migrations
- Automated tests
- Environment-based configuration
Auth API follows a layered backend architecture.
app/
│
├── routers/
│ ↓
│ HTTP layer
│
├── services/
│ ↓
│ Business logic
│
├── repositories/
│ ↓
│ Data access
│
└── database/
↓
PostgreSQL
Responsible for:
- HTTP requests
- Request validation
- Authentication dependencies
- Response serialization
- API routing
app/routers/
Contains application and business logic:
- Authentication workflows
- User management
- Token handling
- Email workflows
app/services/
Responsible for persistence:
- CRUD operations
- Database queries
- User persistence
- Token persistence
app/repositories/
Contains security-sensitive functionality:
- Password hashing
- JWT handling
- Token generation
- Token validation
app/security/
auth-api/
│
├── app/
│ │
│ ├── config/
│ │ ├── __init__.py
│ │ └── settings.py
│ │
│ ├── core/
│ │ ├── database.py
│ │ ├── exceptions.py
│ │ └── logging.py
│ │
│ ├── models/
│ │ ├── base.py
│ │ ├── user.py
│ │ ├── refresh_token.py
│ │ ├── password_reset_token.py
│ │ └── email_verification_token.py
│ │
│ ├── schemas/
│ │ ├── common.py
│ │ ├── user.py
│ │ └── auth.py
│ │
│ ├── repositories/
│ │ ├── base.py
│ │ ├── user.py
│ │ └── token.py
│ │
│ ├── services/
│ │ ├── user.py
│ │ ├── auth.py
│ │ ├── token.py
│ │ └── email.py
│ │
│ ├── routers/
│ │ ├── auth.py
│ │ ├── user.py
│ │ └── health.py
│ │
│ ├── dependencies/
│ │ ├── auth.py
│ │ ├── database.py
│ │ └── services.py
│ │
│ ├── security/
│ │ ├── password.py
│ │ ├── jwt.py
│ │ └── tokens.py
│ │
│ ├── middleware/
│ │ ├── logging.py
│ │ ├── rate_limit.py
│ │ └── security_headers.py
│ │
│ ├── utils/
│ │ ├── validators.py
│ │ └── helpers.py
│ │
│ ├── tests/
│ │ ├── conftest.py
│ │ ├── test_auth.py
│ │ ├── test_user.py
│ │ └── test_validators.py
│ │
│ └── main.py
│
├── migrations/
│ ├── env.py
│ ├── script.py.mako
│ └── versions/
│
├── .env.example
├── .gitignore
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
├── pyproject.toml
├── alembic.ini
├── Makefile
└── README.md
┌──────────────┐
│ Register │
└──────┬───────┘
│
▼
┌────────────────────┐
│ Hash Password │
│ Argon2 │
└─────────┬──────────┘
│
▼
┌────────────────────┐
│ Store User │
│ PostgreSQL │
└─────────┬──────────┘
│
▼
┌────────────────────┐
│ Email Verification │
└─────────┬──────────┘
│
▼
┌────────────────────┐
│ Login │
└─────────┬──────────┘
│
▼
┌────────────────────────────┐
│ Generate Access + Refresh │
│ Tokens │
└────────────┬───────────────┘
│
▼
┌────────────────────────────┐
│ Protected APIs │
└────────────────────────────┘
Access tokens authenticate API requests.
Authorization: Bearer <access_token>Recommended lifetime:
15 minutes
Short-lived access tokens reduce the impact of token compromise.
Refresh tokens are used to obtain new access tokens without requiring the user to log in again.
Auth API supports:
- Database persistence
- Token rotation
- Token revocation
- Session/device association
- Expiration
- Logout invalidation
Recommended lifetime:
30 days
Client
│
│ Refresh Token
▼
/auth/refresh
│
├── Validate token
├── Check expiration
├── Check revocation
├── Rotate token
│
▼
New Access Token
+
New Refresh Token
| Method | Endpoint | Description |
|---|---|---|
POST |
/auth/register |
Create a new account |
POST |
/auth/login |
Authenticate user |
POST |
/auth/refresh |
Refresh access token |
POST |
/auth/logout |
Logout current session |
POST |
/auth/logout-all |
Logout all sessions |
POST |
/auth/verify-email |
Verify email address |
POST |
/auth/forgot-password |
Request password reset |
POST |
/auth/reset-password |
Reset password |
| Method | Endpoint | Description |
|---|---|---|
GET |
/users/me |
Get current user |
PATCH |
/users/me |
Update profile |
PATCH |
/users/password |
Change password |
| Method | Endpoint | Description |
|---|---|---|
GET |
/health |
Health check |
Before running the project, make sure you have:
- Python 3.13+
- PostgreSQL
- Git
- Docker (optional)
git clone https://github.com/ItsWanheda/auth-api.git
cd auth-apipython -m venv .venv
source .venv/bin/activatepython -m venv .venv
.venv\Scripts\activatepip install -r requirements.txtCreate your environment file:
cp .env.example .envWindows PowerShell:
Copy-Item .env.example .envExample configuration:
DATABASE_URL=postgresql://user:password@localhost/authdb
JWT_SECRET_KEY=change_this_in_production
ACCESS_TOKEN_EXPIRE_MINUTES=15
REFRESH_TOKEN_EXPIRE_DAYS=30
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USERNAME=
SMTP_PASSWORD=🔒 Never commit
.envor production secrets to version control.
Run the database migrations:
alembic upgrade headCreate a new migration:
alembic revision --autogenerate -m "add_new_feature"Start the development server:
uvicorn app.main:app --reloadThe API will be available at:
http://localhost:8000
FastAPI automatically generates interactive API documentation.
http://localhost:8000/docs
http://localhost:8000/redoc
Build the containers:
docker compose buildStart the development environment:
docker compose upRun in detached mode:
docker compose up -dStop the environment:
docker compose downRun the test suite:
pytestRun with coverage:
pytest --cov=appIf you use the included Makefile:
make install
make test
make format
make lint- OAuth2 / OpenID Connect
- Google authentication
- GitHub authentication
- Discord authentication
- Two-factor authentication
- WebAuthn / Passkeys
- Device management
- Login history
- Suspicious-login detection
- Advanced rate limiting
- Security audit logs
- Admin dashboard
- Role-based access control
- Permission system
- API keys
- Multi-tenant support
- Microservice integration
Contributions, bug reports, feature requests, and security improvements are welcome.
# Fork the repository
git clone https://github.com/ItsWanheda/auth-api.git
cd auth-api
git checkout -b feature/my-featureMake your changes, then:
git add .
git commit -m "feat: add my feature"
git push origin feature/my-featureFinally, open a Pull Request.
- 🐛 Bug fixes
- 🔐 Security improvements
- ⚡ Performance
- 🧪 Tests
- 📚 Documentation
- ✨ New authentication features
- 🏗️ Architecture improvements
If you discover a security vulnerability, please do not open a public issue with sensitive details.
Instead, report the vulnerability privately through the repository's available security reporting channel.
Security-related contributions are especially welcome.
This project is licensed under the MIT License.
Built with ❤️ by ItsWanheda
- 🐍 Python
- ⚡ FastAPI
- 🐘 PostgreSQL
- 🧩 SQLAlchemy
- 🔑 JWT
- 🛡️ Argon2
- 🐳 Docker
- 🔄 Alembic