Chuyển đến nội dung
Skillpedia
Bảo mật280k · #170

django-security

Skill này làm gì

Skill này giúp bảo vệ website Django của bạn khỏi các tấn công phổ biến. Nó cấu hình website an toàn hơn, đặc biệt khi website đã được đưa vào môi trường thực tế (production).

Khi nào nên dùng

  • ✓Khi thiết lập bảo mật cho website Django của bạn.
  • ✓Khi xem lại quyền hạn của người dùng.
  • ✓Khi chuẩn bị đưa website của bạn vào hoạt động chính thức.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/django-security/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/django-security/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để cấu hình website Django của tôi an toàn hơn khi chạy trên môi trường thực tế?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó áp dụng các thiết lập bảo mật được khuyến nghị, như bảo vệ chống đánh cắp dữ liệu, đảm bảo chỉ người được phép mới truy cập thông tin, và kiểm tra dữ liệu người dùng nhập vào để ngăn mã độc.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Django Security Best Practices

Comprehensive security guidelines for Django applications to protect against common vulnerabilities.

When to Activate

  • Setting up Django authentication and authorization
  • Implementing user permissions and roles
  • Configuring production security settings
  • Reviewing Django application for security issues
  • Deploying Django applications to production

Core Security Settings

Production Settings Configuration

# settings/production.py
import os

DEBUG = False  # CRITICAL: Never use True in production

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

# Security headers
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'

# HTTPS and Cookies
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SAMESITE = 'Lax'

# Secret key (must be set via environment variable)
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
if not SECRET_KEY:
    raise ImproperlyConfigured('DJANGO_SECRET_KEY environment variable is required')

# Password validation
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',
    },
]

Authentication

Custom User Model

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

class User(AbstractUser):
    """Custom user model for better security."""

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

    USERNAME_FIELD = 'email'  # Use email as username
    REQUIRED_FIELDS = ['username']

    class Meta:
        db_table = 'users'
        verbose_name = 'User'
        verbose_name_plural = 'Users'

    def __str__(self):
        return self.email

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

Password Hashing

# Django uses PBKDF2 by default. For stronger security:
PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

Session Management

# Session configuration
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # Or 'db'
SESSION_CACHE_ALIAS = 'default'
SESSION_COOKIE_AGE = 3600 * 24 * 7  # 1 week
SESSION_SAVE_EVERY_REQUEST = False
SESSION_EXPIRE_AT_BROWSER_CLOSE = False  # Better UX, but less secure

Authorization

Permissions

# 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 publish posts'),
            ('can_edit_others', 'Can edit posts of others'),
        ]

    def user_can_edit(self, user):
        """Check if user can edit this post."""
        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  # Return 403 instead of redirect

    def get_queryset(self):
        """Only allow users to edit their own posts."""
        return Post.objects.filter(author=self.request.user)

Custom Permissions

# permissions.py
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    """Allow only owners to edit objects."""

    def has_object_permission(self, request, view, obj):

…
Câu hỏi thường gặp

'CSRF protection' và 'SQL injection prevention' là gì?

Đây là các kỹ thuật ngăn hacker chèn mã độc vào website. CSRF ngăn các website độc hại thực hiện thao tác thay bạn, còn phòng chống SQL injection ngăn chúng đọc hoặc sửa dữ liệu trong cơ sở dữ liệu.

Vì sao 'DEBUG = False' quan trọng trong môi trường thực tế?

Khi DEBUG là 'True', Django hiển thị thông tin lỗi chi tiết mà hacker có thể khai thác. Trong môi trường thực tế, giá trị này nên luôn là 'False' để ẩn các chi tiết đó.

'Security headers' là gì?

Đây là các chỉ thị website gửi tới trình duyệt của người dùng để tăng cường bảo mật, như đảm bảo kết nối luôn an toàn (HTTPS) và ngăn nội dung được hiển thị trên các trang khác.

Chi tiết

Mô tả gốc của tác giả

Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations. Use when reviewing Django authentication, authorization, input handling, or deployment settings.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#170
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự