Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

RBAC Auth API

Role-Based Access Control (RBAC) Authentication API built with Django REST Framework.

Python Django DRF License

Features

  • 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

Quick Start

With Docker (Recommended)

# Clone the repository
git clone https://github.com/yourusername/rbac-auth-api.git
cd rbac-auth-api

# Start all services
docker compose up

That's it! The API will be available at http://localhost:8000

Local Development

# 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

Demo Users

Username Password Role Access Level
admin admin123! Admin Full access
editor editor123! Editor Editor + User endpoints
user user123! User User endpoints only

URLs

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

API Endpoints

Authentication

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

Users

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

Protected (Demo)

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

Usage Examples

Register

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!"
  }'

Login

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"]
  }
}

Access Protected Endpoint

curl http://localhost:8000/api/v1/protected/admin/ \
  -H "Authorization: Bearer <access_token>"

Refresh Token

curl -X POST http://localhost:8000/api/v1/auth/refresh/ \
  -H "Content-Type: application/json" \
  -d '{"refresh": "<refresh_token>"}'

Logout

curl -X POST http://localhost:8000/api/v1/auth/logout/ \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{"refresh": "<refresh_token>"}'

Permission Matrix

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

Project Structure

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

Environment Variables

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

Running Tests

# With Docker
docker compose exec api pytest /tests -v

# Local
cd src && USE_SQLITE=True PYTHONPATH=. pytest ../tests -v

Design Decisions

Why Django Groups for Roles?

Django'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

Why Refresh Token Rotation?

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

Why Redis?

Redis is used for:

  • Token blacklist storage (fast lookups)
  • Rate limiting counters
  • Session caching (future)

Security Considerations

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

Tech Stack

  • 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

License

MIT License - feel free to use this project for learning or as a starting point for your own projects.

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages