django-security

django-security

熱門

Django 安全最佳實務,包含身分驗證、授權、CSRF 防護、SQL 注入防範、XSS 防範以及安全部署設定。

23萬星標
3.5萬分支
更新於 2026/7/14
SKILL.md
readonlyread-only
name
django-security
description

Django 安全最佳實務,包含身分驗證、授權、CSRF 防護、SQL 注入防範、XSS 防範以及安全部署設定。

Django 安全最佳實務

全面的 Django 應用程式安全指南,協助防範常見漏洞。

啟用時機

  • 設定 Django 身分驗證與授權
  • 實作使用者權限與角色
  • 設定生產環境安全設定
  • 審查 Django 應用程式的安全性
  • 將 Django 應用程式部署至生產環境

核心安全設定

生產環境設定

# settings/production.py
import os

DEBUG = False  # 關鍵:生產環境絕對不能設為 True

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')

# 安全標頭
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000  # 1 年
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'

# HTTPS 與 Cookie
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SAMESITE = 'Lax'

# 密鑰(必須透過環境變數設定)
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
if not SECRET_KEY:
    raise ImproperlyConfigured('DJANGO_SECRET_KEY 環境變數為必填')

# 密碼驗證
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 12,
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

身分驗證

自訂使用者模型

# apps/users/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    """自訂使用者模型,提升安全性。"""

    email = models.EmailField(unique=True)
    phone = models.CharField(max_length=20, blank=True)

    USERNAME_FIELD = 'email'  # 使用 email 作為使用者名稱
    REQUIRED_FIELDS = ['username']

    class Meta:
        db_table = 'users'
        verbose_name = '使用者'
        verbose_name_plural = '使用者'

    def __str__(self):
        return self.email

# settings/base.py
AUTH_USER_MODEL = 'users.User'

密碼雜湊

# Django 預設使用 PBKDF2。如需更強的安全性:
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

Session 管理

# Session 設定
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 或 'db'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 3600 * 24 * 7  # 1 週
SESSION_SAVE_EVERY_REQUEST = False
SESSION_EXPIRE_AT_BROWSER_CLOSE = False  # 較佳的使用體驗,但安全性較低

授權

權限

# models.py
from django.db import models
from django.contrib.auth.models import Permission

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        permissions = [
            ('can_publish', '可以發布文章'),
            ('can_edit_others', '可以編輯他人的文章'),
        ]

    def user_can_edit(self, user):
        """檢查使用者是否可以編輯這篇文章。"""
        return self.author == user or user.has_perm('app.can_edit_others')

# views.py
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.views.generic import UpdateView

class PostUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
    model = Post
    permission_required = 'app.can_edit_others'
    raise_exception = True  # 回傳 403 而非重新導向

    def get_queryset(self):
        """只允許使用者編輯自己的文章。"""
        return Post.objects.filter(author=self.request.user)

自訂權限

# permissions.py
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    """只允許擁有者編輯物件。"""

    def has_object_permission(self, request, view, obj):
        # 讀取權限允許任何請求
        if request.method in permissions.SAFE_METHODS:
            return True

        # 寫入權限僅限擁有者
        return obj.author == request.user

class IsAdminOrReadOnly(permissions.BasePermission):
    """管理員可執行任何操作,其他人唯讀。"""

    def has_permission(self, request, view):
        if request.method in permissions.SAFE_METHODS:
            return True
        return request.user and request.user.is_staff

class IsVerifiedUser(permissions.BasePermission):
    """只允許已驗證的使用者。"""

    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated and request.user.is_verified

角色型存取控制(RBAC)

# models.py
from django.contrib.auth.models import AbstractUser, Group

class User(AbstractUser):
    ROLE_CHOICES = [
        ('admin', '管理員'),
        ('moderator', '版主'),
        ('user', '一般使用者'),
    ]
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='user')

    def is_admin(self):
        return self.role == 'admin' or self.is_superuser

    def is_moderator(self):
        return self.role in ['admin', 'moderator']

# Mixins
class AdminRequiredMixin:
    """Mixin 要求管理員角色。"""

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin():
            from django.core.exceptions import PermissionDenied
            raise PermissionDenied
        return super().dispatch(request, *args, **kwargs)

SQL 注入防範

Django ORM 保護

# 良好:Django ORM 自動跳脫參數
def get_user(username):
    return User.objects.get(username=username)  # 安全

# 良好:使用 raw() 搭配參數
def search_users(query):
    return User.objects.raw('SELECT * FROM users WHERE username = %s', [query])

# 不良:絕對不要直接插入使用者輸入
def get_user_bad(username):
    return User.objects.raw(f'SELECT * FROM users WHERE username = {username}')  # 有漏洞!

# 良好:使用 filter 搭配適當跳脫
def get_users_by_email(email):
    return User.objects.filter(email__iexact=email)  # 安全

# 良好:使用 Q 物件處理複雜查詢
from django.db.models import Q
def search_users_complex(query):
    return User.objects.filter(
        Q(username__icontains=query) |
        Q(email__icontains=query)
    )  # 安全

使用 raw() 的額外安全措施

# 如果必須使用原始 SQL,務必使用參數
User.objects.raw(
    'SELECT * FROM users WHERE email = %s AND status = %s',
    [user_input_email, status]
)

XSS 防範

模板跳脫

{# Django 預設會自動跳脫變數 - 安全 #}
{{ user_input }}  {# 已跳脫 HTML #}

{# 僅對可信內容明確標記為安全 #}
{{ trusted_html|safe }}  {# 未跳脫 #}

{# 使用模板過濾器處理安全的 HTML #}
{{ user_input|escape }}  {# 與預設相同 #}
{{ user_input|striptags }}  {# 移除所有 HTML 標籤 #}

{# JavaScript 跳脫 #}
<script>
    var username = {{ username|escapejs }};
</script>

安全字串處理

from django.utils.safestring import mark_safe
from django.utils.html import escape

# 不良:絕對不要未經跳脫就將使用者輸入標記為安全
def render_bad(user_input):
    return mark_safe(user_input)  # 有漏洞!

# 良好:先跳脫,再標記為安全
def render_good(user_input):
    return mark_safe(escape(user_input))

# 良好:使用 format_html 處理含變數的 HTML
from django.utils.html import format_html

def greet_user(username):
    return format_html('<span class="user">{}</span>', escape(username))

HTTP 標頭

# settings.py
SECURE_CONTENT_TYPE_NOSNIFF = True  # 防止 MIME 嗅探
SECURE_BROWSER_XSS_FILTER = True  # 啟用 XSS 過濾器
X_FRAME_OPTIONS = 'DENY'  # 防止點擊劫持

# 自訂中介層
from django.conf import settings

class SecurityHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['X-Content-Type-Options'] = 'nosniff'
        response['X-Frame-Options'] = 'DENY'
        response['X-XSS-Protection'] = '1; mode=block'
        response['Content-Security-Policy'] = "default-src 'self'"
        return response

CSRF 防護

預設 CSRF 防護

# settings.py - CSRF 預設啟用
CSRF_COOKIE_SECURE = True  # 僅透過 HTTPS 傳送
CSRF_COOKIE_HTTPONLY = True  # 防止 JavaScript 存取
CSRF_COOKIE_SAMESITE = 'Lax'  # 在某些情況下防止 CSRF
CSRF_TRUSTED_ORIGINS = ['https://example.com']  # 信任的網域

# 模板使用
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">送出</button>
</form>

# AJAX 請求
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

fetch('/api/endpoint/', {
    method: 'POST',
    headers: {
        'X-CSRFToken': getCookie('csrftoken'),
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data)
});

豁免檢視(謹慎使用)

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt  # 僅在絕對必要時使用!
def webhook_view(request):
    # 來自外部服務的 Webhook
    pass

檔案上傳安全

檔案驗證

import os
import magic  # pip install python-magic
from django.core.exceptions import ValidationError

ALLOWED_MIMES = {
    'image/jpeg', 'image/png', 'image/gif', 'application/pdf',
}

MIME_TO_EXTENSIONS = {
    'image/jpeg': {'.jpg', '.jpeg'},
    'image/png': {'.png'},
    'image/gif': {'.gif'},
    'application/pdf': {'.pdf'},
}

def validate_file_type(value):
    """使用魔術位元組驗證檔案類型,並交叉檢查副檔名。"""
    mime = magic.from_buffer(value.read(2048), mime=True)
    value.seek(0)

    if mime not in ALLOWED_MIMES:
        raise ValidationError('不支援的檔案類型。')

    ext = os.path.splitext(value.name)[1].lower()
    if ext not in MIME_TO_EXTENSIONS.get(mime, set()):
        raise ValidationError('副檔名與檔案內容不符。')

def validate_file_size(value):
    """驗證檔案大小(最大 5MB)。"""
    if value.size > 5 * 1024 * 1024:
        raise ValidationError('檔案過大。最大大小為 5MB。')

# models.py
class Document(models.Model):
    file = models.FileField(
        upload_to='documents/',
        validators=[validate_file_type, validate_file_size]
    )

對於難以安裝 libmagic 的環境(例如最小容器),可使用純 Python 的 filetype 套件作為替代方案:

import os
from django.core.exceptions import ValidationError

import filetype  # pip install filetype

ALLOWED_MIMES = {
    'image/jpeg', 'image/png', 'image/gif', 'application/pdf',
}

MIME_TO_EXTENSIONS = {
    'image/jpeg': {'.jpg', '.jpeg'},
    'image/png': {'.png'},
    'image/gif': {'.gif'},
    'application/pdf': {'.pdf'},
}

def validate_file_type(value):
    """使用魔術位元組驗證檔案類型。"""
    kind = filetype.guess(value.read(2048))
    value.seek(0)

    if kind is None or kind.mime not in ALLOWED_MIMES:
        raise ValidationError('不支援的檔案類型。')

    ext = os.path.splitext(value.name)[1].lower()
    if ext not in MIME_TO_EXTENSIONS.get(kind.mime, set()):
        raise ValidationError('副檔名與檔案內容不符。')

安全的檔案儲存

# settings.py
MEDIA_ROOT = '/var/www/media/'
MEDIA_URL = '/media/'

# 在生產環境中使用獨立網域存放媒體檔案
MEDIA_DOMAIN = 'https://media.example.com'

# 不要直接提供使用者上傳的檔案
# 使用 whitenoise 或 CDN 處理靜態檔案
# 使用獨立伺服器或 S3 存放媒體檔案

API 安全

速率限制

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day',
        'upload': '10/hour',
    }
}

# 自訂節流
from rest_framework.throttling import UserRateThrottle

class BurstRateThrottle(UserRateThrottle):
    scope = 'burst'
    rate = '60/min'

class SustainedRateThrottle(UserRateThrottle):
    scope = 'sustained'
    rate = '1000/day'

API 身分驗證

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

# views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated

@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def protected_view(request):
    return Response({'message': '您已通過身分驗證'})

安全標頭

內容安全政策

# settings.py
CSP_DEFAULT_SRC = "'self'"
CSP_SCRIPT_SRC = "'self' https://cdn.example.com"
CSP_STYLE_SRC = "'self' 'unsafe-inline'"
CSP_IMG_SRC = "'self' data: https:"
CSP_CONNECT_SRC = "'self' https://api.example.com"

# 中介層
class CSPMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['Content-Security-Policy'] = (
            f"default-src {CSP_DEFAULT_SRC}; "
            f"script-src {CSP_SCRIPT_SRC}; "
            f"style-src {CSP_STYLE_SRC}; "
            f"img-src {CSP_IMG_SRC}; "
            f"connect-src {CSP_CONNECT_SRC}"
        )
        return response

環境變數

管理機密

# 使用 python-decouple 或 django-environ
import environ

env = environ.Env(
    # 設定型別轉換與預設值
    DEBUG=(bool, False)
)

# 讀取 .env 檔案
environ.Env.read_env()

SECRET_KEY = env('DJANGO_SECRET_KEY')
DATABASE_URL = env('DATABASE_URL')
ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')

# .env 檔案(絕對不要提交此檔案)
DEBUG=False
SECRET_KEY=your-secret-key-here
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
ALLOWED_HOSTS=example.com,www.example.com

記錄安全事件

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': '/var/log/django/security.log',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.security': {
            'handlers': ['file', 'console'],
            'level': 'WARNING',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': False,
        },
    },
}

快速安全檢查清單

檢查項目 說明
DEBUG = False 生產環境絕對不能開啟 DEBUG
僅限 HTTPS 強制 SSL,安全 Cookie
強密鑰 使用環境變數設定 SECRET_KEY
密碼驗證 啟用所有密碼驗證器
CSRF 防護 預設啟用,請勿關閉
XSS 防範 Django 自動跳脫,勿對使用者輸入使用 &#124;safe
SQL 注入 使用 ORM,絕不在查詢中串接字串
檔案上傳 驗證檔案類型與大小
速率限制 對 API 端點進行節流
安全標頭 CSP、X-Frame-Options、HSTS
記錄 記錄安全事件
更新 保持 Django 與相依套件更新

請記住:安全是一個過程,而非產品。定期審查並更新您的安全實務。