$npx -y skills add skateddu/claude-code-python-setup --skill django-securityDjango security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations.
| 1 | # Django Security Best Practices |
| 2 | |
| 3 | Comprehensive security guidelines for Django applications to protect against common vulnerabilities. |
| 4 | |
| 5 | ## When to Activate |
| 6 | |
| 7 | - Setting up Django authentication and authorization |
| 8 | - Implementing user permissions and roles |
| 9 | - Configuring production security settings |
| 10 | - Reviewing Django application for security issues |
| 11 | - Deploying Django applications to production |
| 12 | |
| 13 | ## Core Security Settings |
| 14 | |
| 15 | ### Production Settings Configuration |
| 16 | |
| 17 | ```python |
| 18 | # settings/production.py |
| 19 | import os |
| 20 | |
| 21 | DEBUG = False # CRITICAL: Never use True in production |
| 22 | |
| 23 | ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',') |
| 24 | |
| 25 | # Security headers |
| 26 | SECURE_SSL_REDIRECT = True |
| 27 | SESSION_COOKIE_SECURE = True |
| 28 | CSRF_COOKIE_SECURE = True |
| 29 | SECURE_HSTS_SECONDS = 31536000 # 1 year |
| 30 | SECURE_HSTS_INCLUDE_SUBDOMAINS = True |
| 31 | SECURE_HSTS_PRELOAD = True |
| 32 | SECURE_CONTENT_TYPE_NOSNIFF = True |
| 33 | SECURE_BROWSER_XSS_FILTER = True |
| 34 | X_FRAME_OPTIONS = 'DENY' |
| 35 | |
| 36 | # HTTPS and Cookies |
| 37 | SESSION_COOKIE_HTTPONLY = True |
| 38 | CSRF_COOKIE_HTTPONLY = True |
| 39 | SESSION_COOKIE_SAMESITE = 'Lax' |
| 40 | CSRF_COOKIE_SAMESITE = 'Lax' |
| 41 | |
| 42 | # Secret key (must be set via environment variable) |
| 43 | SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') |
| 44 | if not SECRET_KEY: |
| 45 | raise ImproperlyConfigured('DJANGO_SECRET_KEY environment variable is required') |
| 46 | |
| 47 | # Password validation |
| 48 | AUTH_PASSWORD_VALIDATORS = [ |
| 49 | { |
| 50 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', |
| 51 | }, |
| 52 | { |
| 53 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', |
| 54 | 'OPTIONS': { |
| 55 | 'min_length': 12, |
| 56 | } |
| 57 | }, |
| 58 | { |
| 59 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', |
| 60 | }, |
| 61 | { |
| 62 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', |
| 63 | }, |
| 64 | ] |
| 65 | ``` |
| 66 | |
| 67 | ## Authentication |
| 68 | |
| 69 | ### Custom User Model |
| 70 | |
| 71 | ```python |
| 72 | # apps/users/models.py |
| 73 | from django.contrib.auth.models import AbstractUser |
| 74 | from django.db import models |
| 75 | |
| 76 | class User(AbstractUser): |
| 77 | """Custom user model for better security.""" |
| 78 | |
| 79 | email = models.EmailField(unique=True) |
| 80 | phone = models.CharField(max_length=20, blank=True) |
| 81 | |
| 82 | USERNAME_FIELD = 'email' # Use email as username |
| 83 | REQUIRED_FIELDS = ['username'] |
| 84 | |
| 85 | class Meta: |
| 86 | db_table = 'users' |
| 87 | verbose_name = 'User' |
| 88 | verbose_name_plural = 'Users' |
| 89 | |
| 90 | def __str__(self): |
| 91 | return self.email |
| 92 | |
| 93 | # settings/base.py |
| 94 | AUTH_USER_MODEL = 'users.User' |
| 95 | ``` |
| 96 | |
| 97 | ### Password Hashing |
| 98 | |
| 99 | ```python |
| 100 | # Django uses PBKDF2 by default. For stronger security: |
| 101 | PASSWORD_HASHERS = [ |
| 102 | 'django.contrib.auth.hashers.Argon2PasswordHasher', |
| 103 | 'django.contrib.auth.hashers.PBKDF2PasswordHasher', |
| 104 | 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', |
| 105 | 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', |
| 106 | ] |
| 107 | ``` |
| 108 | |
| 109 | ### Session Management |
| 110 | |
| 111 | ```python |
| 112 | # Session configuration |
| 113 | SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # Or 'db' |
| 114 | SESSION_CACHE_ALIAS = 'default' |
| 115 | SESSION_COOKIE_AGE = 3600 * 24 * 7 # 1 week |
| 116 | SESSION_SAVE_EVERY_REQUEST = False |
| 117 | SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Better UX, but less secure |
| 118 | ``` |
| 119 | |
| 120 | ## Authorization |
| 121 | |
| 122 | ### Permissions |
| 123 | |
| 124 | ```python |
| 125 | # models.py |
| 126 | from django.db import models |
| 127 | from django.contrib.auth.models import Permission |
| 128 | |
| 129 | class Post(models.Model): |
| 130 | title = models.CharField(max_length=200) |
| 131 | content = models.TextField() |
| 132 | author = models.ForeignKey(User, on_delete=models.CASCADE) |
| 133 | |
| 134 | class Meta: |
| 135 | permissions = [ |
| 136 | ('can_publish', 'Can publish posts'), |
| 137 | ('can_edit_others', 'Can edit posts of others'), |
| 138 | ] |
| 139 | |
| 140 | def user_can_edit(self, user): |
| 141 | """Check if user can edit this post.""" |
| 142 | return self.author == user or user.has_perm('app.can_edit_others') |
| 143 | |
| 144 | # views.py |
| 145 | from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin |
| 146 | from django.views.generic import UpdateView |
| 147 | |
| 148 | class PostUpdateView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): |
| 149 | model = Post |
| 150 | permission_required = 'app.can_edit_others' |
| 151 | raise_exception = True # Return 403 instead of redirect |
| 152 | |
| 153 | def get_queryset(self): |
| 154 | """Only allow users to edit their own posts.""" |
| 155 | return Post.objects.filter(author=self.request.user) |
| 156 | ``` |
| 157 | |
| 158 | ### Custom Permissions |
| 159 | |
| 160 | ```python |
| 161 | # permissions.py |
| 162 | from rest_framework import permissions |
| 163 | |
| 164 | class IsOwnerOrReadOnly(permissions.BasePermission): |
| 165 | """Allow only owners to edit objects.""" |
| 166 | |
| 167 | def has_object_permission(self, request, view, obj): |
| 168 | # Read permissions allowed for any request |
| 169 | if request.method in permissions.SAFE_METHODS: |
| 170 | return True |
| 171 | |
| 172 | # Write permissions only for owner |
| 173 | return obj.author == request.user |
| 174 | |
| 175 | class IsAdminOrReadOnly(permissions.BasePermission): |
| 176 | """Allow admins to do anything, others read-only.""" |