Chuyển đến nội dung chính

Lesson 12: Security Best Practices

OWASP Top 10 in Django. XSS, CSRF, SQL Injection prevention. Security middleware, Content Security Policy. Rate limiting, input sanitization, secure headers.

💻 Programming — Lesson 12 Lesson 12: Security Best Practices

Django: From Basics to Advanced

Part 3: Authentication & Security

xdev.asia

1. Security Settings

# settings.py — Production security
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True

SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_AGE = 3600

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True

X_FRAME_OPTIONS = 'DENY'

2. SQL Injection Prevention

# SAI — vulnerable
Product.objects.raw(f"SELECT * FROM products WHERE name = '{name}'")

# ĐÚNG — parameterized query
Product.objects.raw("SELECT * FROM products WHERE name = %s", [name])

# ĐÚNG — ORM (tự escape)
Product.objects.filter(name=name)

# Raw SQL an toàn
from django.db import connection
with connection.cursor() as cursor:
    cursor.execute("SELECT * FROM products WHERE price > %s", [min_price])

3. XSS Prevention

# Django template auto-escapes by default
{{ user_input }}  {# Đã escape #}
{{ user_input|safe }}  {# NGUY HIỂM — tránh dùng #}

# Bleach để sanitize HTML
import bleach
clean_html = bleach.clean(
    user_html,
    tags=['p', 'b', 'i', 'a', 'ul', 'li'],
    attributes={'a': ['href', 'title']},
)

4. Content Security Policy

pip install django-csp
# settings.py
MIDDLEWARE = [..., 'csp.middleware.CSPMiddleware']

CSP_DEFAULT_SRC = ("'self'",)
CSP_SCRIPT_SRC = ("'self'", 'cdn.example.com')
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'")
CSP_IMG_SRC = ("'self'", 'data:', '*.amazonaws.com')

5. Input Validation & Sanitization

from django.core.validators import (
    RegexValidator, FileExtensionValidator,
)

class UserProfile(models.Model):
    phone = models.CharField(
        max_length=15,
        validators=[RegexValidator(r'^\+?[0-9]{9,15}$')],
    )
    avatar = models.FileField(
        validators=[FileExtensionValidator(allowed_extensions=['jpg', 'png', 'webp'])],
    )

# File upload size limit
FILE_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024  # 5MB
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024

6. Security Checklist

# Django security check
python manage.py check --deploy
SectionStatus
DEBUG = False✅
SECRET_KEY from env✅
ALLOWED_HOSTS set✅
HTTPS only✅
CSRF enabled✅
SQL parameterized✅
File upload validated✅
Security headers✅

Next article: Django Admin Customization.