A backend authentication and authorization service built with Python and Django, providing secure user authentication, JWT-based API access control, and user/account management for web applications and business platforms.
The service is designed as a standalone authentication layer that can be integrated with multiple frontend applications and backend services through REST APIs.
- Overview
- Key Features
- Technology Stack
- Architecture
- Authentication Flow
- API Endpoints
- Security Considerations
- Project Structure
- Local Development
- Docker Deployment
- Testing
- API Documentation
- What This Project Demonstrates
- Status
- License
This service provides a central authentication layer for applications that need secure user access, account management, and authorization. It follows a service-oriented approach, allowing authentication and user management to remain separate from the business logic of individual applications.
- User registration with email verification
- JWT-based authentication (access and refresh tokens)
- Password management (change, reset via email)
- Role-based access control (RBAC)
- User profile management
- Secure REST API endpoints with CORS support
- Admin user management
- OpenAPI/Swagger documentation
- Environment-based configuration
- Docker-ready deployment
| Area | Technology |
|---|---|
| Language | Python 3.11 |
| Framework | Django 4.2 LTS |
| API | Django REST Framework |
| Authentication | JWT (djangorestframework-simplejwt) |
| Database | PostgreSQL |
| API Documentation | OpenAPI/Swagger (drf-spectacular) |
| CORS | django-cors-headers |
| Deployment | Docker / Gunicorn |
| Testing | Django Test Framework |
The authentication service acts as a central API responsible for identity and access management.
┌─────────────────────┐
│ Web / Mobile App │
└──────────┬──────────┘
│
│ HTTPS / REST API
▼
┌─────────────────────┐
│ Authentication API │
│ Django │
└──────────┬──────────┘
│
┌────────────┼────────────┐
│ │ │
▼ ▼ ▼
Authentication Users Permissions
│ │ │
└────────────┼────────────┘
▼
┌─────────────────────┐
│ PostgreSQL │
└─────────────────────┘
User
│
▼
Frontend Application
│
│ Login credentials
▼
Authentication API
│
│ Validate credentials
▼
User / Authentication System
│
│ Generate access token + refresh token
▼
Frontend
│
│ Authorization: Bearer <access_token>
▼
Protected API
The API validates the user's credentials and issues a JWT access token (short-lived) and refresh token (long-lived). The access token is used for subsequent API requests, and the refresh token can be used to obtain a new access token when it expires.
All API endpoints are under /api/auth/.
| Method | Endpoint | Description | Auth Required | Permissions |
|---|---|---|---|---|
| POST | /api/auth/register/ |
Register a new user account | No | AllowAny |
| POST | /api/auth/login/ |
Login with email and password | No | AllowAny |
| POST | /api/auth/logout/ |
Logout and clear session | Yes | IsAuthenticated |
| POST | /api/auth/token/refresh/ |
Refresh access token | No | AllowAny |
| POST | /api/auth/token/verify/ |
Verify a token's validity | No | AllowAny |
| GET | /api/auth/profile/ |
Get authenticated user's profile | Yes | IsAuthenticated |
| PUT | /api/auth/profile/ |
Update user profile | Yes | IsOwnerOrAdmin |
| POST | /api/auth/password/change/ |
Change current password | Yes | IsAuthenticated |
| POST | /api/auth/password/reset/ |
Request password reset email | No | AllowAny |
| POST | /api/auth/password/reset/confirm/ |
Reset password with token | No | AllowAny |
| GET | /api/auth/roles/ |
List all roles | Yes | IsAdmin |
| GET | /api/auth/users/ |
List all users | Yes | IsAdmin |
| GET | /api/auth/users/<id>/ |
Get a specific user | Yes | IsAdmin |
| DELETE | /api/auth/users/<id>/ |
Delete a specific user | Yes | IsAdmin |
curl -X POST http://localhost:8000/api/auth/register/ \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"first_name": "John",
"last_name": "Doe",
"password": "SecurePass123!",
"confirm_password": "SecurePass123!"
}'curl -X POST http://localhost:8000/api/auth/login/ \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePass123!"
}'Response:
{
"access": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refresh": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": 1,
"email": "user@example.com",
"first_name": "John",
"last_name": "Doe",
"is_active": true,
"is_verified": false,
"date_joined": "2024-01-01T00:00:00Z",
"roles": []
}
}curl -X GET http://localhost:8000/api/auth/profile/ \
-H "Authorization: Bearer <access_token>"Security is treated as a core part of the service:
- Password hashing: Django's built-in PBKDF2 password hashing
- Token-based authentication: Short-lived JWT access tokens (30 min default)
- Protected API endpoints: All endpoints require authentication by default
- Permission-based access control: Custom permission classes (
IsAdmin,IsVerified,IsOwnerOrAdmin) - Input validation: All inputs validated through DRF serializers
- Authentication failure handling: Descriptive error messages without leaking user data
- CORS configuration: Configurable allowed origins
- Secure production configuration: Secret key and all credentials via environment variables
- Separation of secrets: No credentials committed to the repository
- Token expiration: Access tokens expire; refresh tokens are rotated on each use
- Inactive user rejection: JWT authentication rejects inactive user accounts
auth/
├── manage.py
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
├── .env.example
├── .gitignore
├── README.md
├── auth/ # Django project package
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
├── authentication/ # Authentication app
│ ├── __init__.py
│ ├── apps.py
│ ├── admin.py
│ ├── models.py
│ ├── serializers.py
│ ├── views.py
│ ├── urls.py
│ ├── backend.py
│ ├── permissions.py
│ ├── tests.py
│ └── migrations/
│ ├── __init__.py
│ └── 0001_initial.py
└── venv/ # Python virtual environment (gitignored)
git clone https://github.com/msyoki/auth.git
cd authpython -m venv venvActivate it on Windows:
venv\Scripts\activateOn Linux/macOS:
source venv/bin/activatepip install -r requirements.txtCopy the example environment file and edit it:
cp .env.example .envEdit .env with your configuration. For local development, the included .env uses SQLite:
SECRET_KEY=your-secret-key
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1
DATABASE_ENGINE=django.db.backends.sqlite3
DATABASE_NAME=db.sqlite3
JWT_SIGNING_KEY=your-jwt-secret-keyFor production with PostgreSQL:
DEBUG=False
DATABASE_ENGINE=django.db.backends.postgresql
DATABASE_NAME=your_database
DATABASE_USER=your_user
DATABASE_PASSWORD=your_password
DATABASE_HOST=db
DATABASE_PORT=5432python manage.py migratepython manage.py createsuperuserpython manage.py runserverThe API will be available at http://localhost:8000/api/auth/.
# Copy environment file
cp .env.example .env
# Start services
docker compose up --buildThis starts:
- PostgreSQL on port 5432
- Django application on port 8000
docker build -t auth-api .
docker run -p 8000:8000 --env-file .env auth-apiRun the test suite:
python manage.py testRun tests with verbose output:
python manage.py test -v 2Run specific test module:
python manage.py test authentication.testsThe API is self-documenting via OpenAPI/Swagger. Once the server is running:
- Swagger UI:
http://localhost:8000/api/docs/ - ReDoc:
http://localhost:8000/api/docs/redoc/ - OpenAPI Schema:
http://localhost:8000/api/schema/
- Backend development with Python and Django (4.2 LTS)
- REST API development with Django REST Framework
- JWT-based authentication and authorization
- Database-driven applications with PostgreSQL
- API security (JWT, permissions, CORS, password hashing)
- Service-oriented architecture (standalone auth service)
- Frontend/backend integration via REST API
- Environment-based configuration (no hardcoded secrets)
- Production deployment considerations (Docker, Gunicorn, PostgreSQL)
- Role-based access control (RBAC)
- Password management (change and reset flows)
- Designing reusable backend services
- OpenAPI/Swagger documentation with drf-spectacular
- Custom permission classes
- Custom user model with email-based authentication
Active development / maintained
This repository represents a public example of backend architecture and authentication development. Production implementations may contain additional functionality and configurations not included here.
See the repository license for usage and distribution terms.