Role-Based Access Control (RBAC) Authentication API built with Django REST Framework.
-
Authentication
- User registration with email verification
- JWT-based authentication (access + refresh tokens)
- Refresh token rotation with blacklist
- Logout (single session / all sessions)
- Rate limiting on login endpoint
-
Authorization (RBAC)
- Three roles: Admin, Editor, User
- Route-level permission control
- Custom permission classes
-
Security
- Password hashing (PBKDF2)
- Short-lived access tokens (15 min)
- Refresh token rotation prevents replay attacks
- CORS configuration
-
Developer Experience
- Interactive Test UI
- OpenAPI/Swagger documentation
- Docker ready (single command setup)
- Comprehensive test suite
# Clone the repository
git clone https://github.com/yourusername/rbac-auth-api.git
cd rbac-auth-api
# Start all services
docker compose upThat's it! The API will be available at http://localhost:8000
# Create virtual environment
python -m venv venv
source venv/bin/activate # Linux/Mac
# or: venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Set environment variables
export USE_SQLITE=True
export DJANGO_DEBUG=True
# Run migrations and seed data
cd src
python manage.py migrate
python manage.py seed_roles --with-users
# Start server
python manage.py runserver| Username | Password | Role | Access Level |
|---|---|---|---|
admin |
admin123! |
Admin | Full access |
editor |
editor123! |
Editor | Editor + User endpoints |
user |
user123! |
User | User endpoints only |
| URL | Description |
|---|---|
http://localhost:8000/ |
Interactive Test UI |
http://localhost:8000/api/docs/ |
Swagger Documentation |
http://localhost:8000/api/redoc/ |
ReDoc Documentation |
http://localhost:8000/health/ |
Health Check |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/v1/auth/register/ |
Register new user | No |
POST |
/api/v1/auth/login/ |
Login, get tokens | No |
POST |
/api/v1/auth/refresh/ |
Refresh access token | No |
POST |
/api/v1/auth/logout/ |
Logout current session | Yes |
POST |
/api/v1/auth/logout-all/ |
Logout all sessions | Yes |
| Method | Endpoint | Description | Role |
|---|---|---|---|
GET |
/api/v1/users/me/ |
Get current user | Any |
GET |
/api/v1/users/ |
List all users | Admin |
PATCH |
/api/v1/users/{id}/role/ |
Update user role | Admin |
| Method | Endpoint | Required Role |
|---|---|---|
GET |
/api/v1/protected/admin/ |
Admin only |
GET |
/api/v1/protected/editor/ |
Editor, Admin |
GET |
/api/v1/protected/user/ |
Any authenticated |
curl -X POST http://localhost:8000/api/v1/auth/register/ \
-H "Content-Type: application/json" \
-d '{
"username": "newuser",
"email": "[email protected]",
"password": "SecurePass123!",
"password_confirm": "SecurePass123!"
}'curl -X POST http://localhost:8000/api/v1/auth/login/ \
-H "Content-Type: application/json" \
-d '{
"username": "admin",
"password": "admin123!"
}'Response:
{
"access": "eyJhbGciOiJIUzI1NiIs...",
"refresh": "eyJhbGciOiJIUzI1NiIs...",
"user": {
"id": 1,
"username": "admin",
"email": "[email protected]",
"roles": ["Admin"]
}
}curl http://localhost:8000/api/v1/protected/admin/ \
-H "Authorization: Bearer <access_token>"curl -X POST http://localhost:8000/api/v1/auth/refresh/ \
-H "Content-Type: application/json" \
-d '{"refresh": "<refresh_token>"}'curl -X POST http://localhost:8000/api/v1/auth/logout/ \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{"refresh": "<refresh_token>"}'| Endpoint | Admin | Editor | User | Anonymous |
|---|---|---|---|---|
/auth/register/ |
- | - | - | Yes |
/auth/login/ |
- | - | - | Yes |
/users/me/ |
Yes | Yes | Yes | No |
/users/ |
Yes | No | No | No |
/users/{id}/role/ |
Yes | No | No | No |
/protected/admin/ |
Yes | No | No | No |
/protected/editor/ |
Yes | Yes | No | No |
/protected/user/ |
Yes | Yes | Yes | No |
rbac-auth-api/
├── src/
│ ├── config/ # Django settings
│ │ ├── settings.py
│ │ ├── urls.py
│ │ └── wsgi.py
│ ├── apps/
│ │ ├── authentication/ # Auth endpoints
│ │ │ ├── views.py
│ │ │ ├── serializers.py
│ │ │ └── urls.py
│ │ ├── users/ # User management
│ │ │ ├── views.py
│ │ │ ├── serializers.py
│ │ │ └── urls.py
│ │ └── rbac/ # Permissions & demo endpoints
│ │ ├── permissions.py
│ │ ├── views.py
│ │ └── management/commands/seed_roles.py
│ ├── templates/
│ │ └── test_ui.html # Interactive test UI
│ └── manage.py
├── tests/
│ ├── conftest.py # Pytest fixtures
│ ├── test_auth.py # Auth tests
│ └── test_rbac.py # RBAC tests
├── docker-compose.yml
├── Dockerfile
├── requirements.txt
└── README.md
| Variable | Default | Description |
|---|---|---|
DJANGO_SECRET_KEY |
(required) | Django secret key |
DJANGO_DEBUG |
True |
Debug mode |
DJANGO_ALLOWED_HOSTS |
localhost,127.0.0.1 |
Allowed hosts |
POSTGRES_DB |
rbac_db |
Database name |
POSTGRES_USER |
rbac_user |
Database user |
POSTGRES_PASSWORD |
rbac_password |
Database password |
POSTGRES_HOST |
db |
Database host |
REDIS_URL |
redis://redis:6379/0 |
Redis URL |
JWT_ACCESS_TOKEN_LIFETIME_MINUTES |
15 |
Access token lifetime |
JWT_REFRESH_TOKEN_LIFETIME_DAYS |
7 |
Refresh token lifetime |
USE_SQLITE |
False |
Use SQLite instead of PostgreSQL |
# With Docker
docker compose exec api pytest /tests -v
# Local
cd src && USE_SQLITE=True PYTHONPATH=. pytest ../tests -vDjango's built-in Group model provides a simple and battle-tested way to implement roles. For an MVP, this approach:
- Requires no additional models
- Integrates seamlessly with Django admin
- Can be easily extended to support multiple roles per user
Refresh token rotation with blacklisting provides:
- Stolen Token Detection: If a refresh token is used twice, we know it was compromised
- Limited Window: Even if stolen, tokens have limited validity
- Clean Logout: Revoking refresh tokens immediately invalidates sessions
Redis is used for:
- Token blacklist storage (fast lookups)
- Rate limiting counters
- Session caching (future)
| Threat | Mitigation |
|---|---|
| Brute Force | Rate limiting (5 attempts/minute on login) |
| Token Theft | Short-lived access tokens (15 min) |
| Replay Attack | Refresh token rotation + blacklist |
| XSS | HttpOnly cookies (if using cookie auth) |
| CSRF | API-only, no cookie auth by default |
- Backend: Django 4.2 + Django REST Framework 3.14
- Auth: djangorestframework-simplejwt
- Database: PostgreSQL 15
- Cache: Redis 7
- Docs: drf-spectacular (OpenAPI 3.0)
- Testing: pytest + pytest-django
- Container: Docker + Docker Compose
MIT License - feel free to use this project for learning or as a starting point for your own projects.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request