Skip to main content

A Django middleware that sanitizes incoming request data to prevent XSS.

Project description

django-sanitizer

A lightweight, configurable Django middleware that automatically sanitizes all incoming request data (JSON, form-data, query params) to protect your application against XSS, HTML injection, and unsafe attributes.

Built with Bleach, easy to install, easy to extend, and safe by default.


🛡 How It Works

The middleware intercepts the request before it reaches your views:

  1. Extracts request data (JSON, form-data, GET params)
  2. Sanitizes all values using allowed tags + attributes
  3. Places sanitized result in request.sanitized_data
  4. Your view receives only safe data

This allows cleaning without modifying Django internals.


🚀 Features

  • 🔒 Sanitizes JSON bodies, form-data, and query parameters
  • 🧼 Removes unsafe HTML tags, scripts, event handlers (e.g., onerror)
  • 🎯 Fully configurable via Django settings
  • 📝 Optional HTML response sanitization
  • 🛠 Zero configuration required — works out of the box
  • 🧪 Comes with testing utilities and easy middleware integration

📦 Installation

pip install django-sanitizer

Or install your local dev version:

pip install -e .

⚙️ Setup

Add the middleware to your Django settings:

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django_sanitizers.middleware.SanitizerMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...
]

🔧 Configuration Options (Optional)

Add to settings.py only if you want customization:

SANITIZER_CONFIG = {
    # Define exactly which tags you want to KEEP
    'ALLOWED_TAGS': ['b', 'i', 'u', 'p', 'br'], 
    
    # Define allowed attributes (optional)
    'ALLOWED_ATTRIBUTES': {
        'a': ['href', 'title'],
        'img': ['src', 'alt']
    },
    
    # Security fields to skip
    'SKIP_FIELDS': {'password', 'password_confirmation', 'token', 'access_token', 'refresh_token','secret_key'},
    
    'STRIP': True
}

🧪 Example

Request Body:

{
  "bio": "<script>alert(1)</script><b>Hello</b>"
}

Sanitized Output:

{
  "bio": "<b>Hello</b>"
}

🧪 Django Views Example

JSON Example Endpoint

# views.py
from django.http import JsonResponse

def echo_json(request):
    return JsonResponse(request.sanitized_data)

Form Example Endpoint

def form_view(request):
    return JsonResponse(request.sanitized_data)

🧪 Testing in Postman

For JSON:

  • Method: POST
  • URL: /echo-json/
  • Headers: Content-Type: application/json
  • Body (raw JSON):
{"bio":"<img src=x onerror=alert(1)>hello"}

You should receive:

{"bio":"hello"}

📁 Project Structure (Package Only)

django_sanitizer/
│
├── __init__.py
├── sanitizer.py
└── middleware.py

🛠 Development

python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pip install -e .

Run tests:

pytest

⭐ Support the Project

If this package helps you, please ⭐ star the repository on GitHub once published!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_sanitizers-0.1.3.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_sanitizers-0.1.3-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file django_sanitizers-0.1.3.tar.gz.

File metadata

  • Download URL: django_sanitizers-0.1.3.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for django_sanitizers-0.1.3.tar.gz
Algorithm Hash digest
SHA256 ce0568428ef05e02b4b1019bbb65f3976f2ea336f70cf23c26877dfab3e67e82
MD5 145a51fd5e0deec2cab7a2cb88bb46f9
BLAKE2b-256 cb564c38d0b3400a7d89db94a41ab52443f0a0f544b9727f4794c4287ae9c59a

See more details on using hashes here.

File details

Details for the file django_sanitizers-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for django_sanitizers-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 206dd39234b02c9180c32653ce22bd79b843b542fc8ac5c0481d2fd4c39c7b29
MD5 dbc5e2cb495b571d6160a57132c151aa
BLAKE2b-256 dacb77cc1961cea421ad8cebd2ab5a17023a74e1ee4b3b1a6f8f315c43bb326a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page