Skip to content
msyokiPublic

About

Secure authentication & authorization service built with Django 4.2 and Django REST Framework. JWT-based API authentication with RBAC, password management, role-based access control, and Swagger/OpenAPI docs. Docker-ready with PostgreSQL.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

Authentication & Authorization Service

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.

Table of Contents

Overview

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.

Key Features

  • 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

Technology Stack

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

Architecture

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      │
                    └─────────────────────┘

Authentication Flow

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.

API Endpoints

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

Example: Registration

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

Example: Login

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

Example: Access Protected Endpoint

curl -X GET http://localhost:8000/api/auth/profile/ \
  -H "Authorization: Bearer <access_token>"

Security Considerations

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

Project Structure

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)

Local Development

1. Clone the repository

git clone https://github.com/msyoki/auth.git
cd auth

2. Create a virtual environment

python -m venv venv

Activate it on Windows:

venv\Scripts\activate

On Linux/macOS:

source venv/bin/activate

3. Install dependencies

pip install -r requirements.txt

4. Configure environment variables

Copy the example environment file and edit it:

cp .env.example .env

Edit .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-key

For 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=5432

5. Run migrations

python manage.py migrate

6. Create a superuser (optional)

python manage.py createsuperuser

7. Start the development server

python manage.py runserver

The API will be available at http://localhost:8000/api/auth/.

Docker Deployment

Using Docker Compose

# Copy environment file
cp .env.example .env

# Start services
docker compose up --build

This starts:

  • PostgreSQL on port 5432
  • Django application on port 8000

Manual Docker Build

docker build -t auth-api .
docker run -p 8000:8000 --env-file .env auth-api

Testing

Run the test suite:

python manage.py test

Run tests with verbose output:

python manage.py test -v 2

Run specific test module:

python manage.py test authentication.tests

API Documentation

The 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/

What This Project Demonstrates

  • 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

Status

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.

License

See the repository license for usage and distribution terms.

About

Secure authentication & authorization service built with Django 4.2 and Django REST Framework. JWT-based API authentication with RBAC, password management, role-based access control, and Swagger/OpenAPI docs. Docker-ready with PostgreSQL.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages