0
0
DjangoHow-ToBeginner · 4 min read

How to Secure Django Application: Best Practices and Examples

To secure a Django application, use SECURE_SSL_REDIRECT to enforce HTTPS, enable security middleware like SecurityMiddleware, and set secure cookie flags such as SESSION_COOKIE_SECURE. Also, keep DEBUG = False in production and use strong secret keys.
📐

Syntax

These are key settings and middleware to secure a Django app:

  • SECURE_SSL_REDIRECT = True: Redirects all HTTP requests to HTTPS.
  • SESSION_COOKIE_SECURE = True: Ensures cookies are sent only over HTTPS.
  • CSRF_COOKIE_SECURE = True: Protects CSRF cookie over HTTPS.
  • SECURE_HSTS_SECONDS = 3600: Enables HTTP Strict Transport Security (HSTS) for specified seconds.
  • SecurityMiddleware: Middleware that adds several security headers.
  • DEBUG = False: Disables debug mode in production to avoid leaking sensitive info.
python
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600
DEBUG = False
💻

Example

This example shows a minimal settings.py snippet to enable HTTPS redirection, secure cookies, and security middleware in Django.

python
from django.core.management.utils import get_random_secret_key

SECRET_KEY = get_random_secret_key()

DEBUG = False

ALLOWED_HOSTS = ['yourdomain.com']

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600

# Additional recommended settings
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
Output
No direct output; Django app will redirect HTTP to HTTPS and set secure cookies.
⚠️

Common Pitfalls

Common mistakes when securing Django apps include:

  • Leaving DEBUG = True in production, which exposes sensitive error details.
  • Not setting ALLOWED_HOSTS, allowing HTTP Host header attacks.
  • Forgetting to enable SecurityMiddleware, missing important security headers.
  • Not using HTTPS or not setting secure cookie flags, risking cookie theft.
python
## Wrong way (insecure settings)
DEBUG = True
ALLOWED_HOSTS = []  # Allows all hosts

# Missing SecurityMiddleware
MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
]

SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False

## Right way (secure settings)
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com']

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
📊

Quick Reference

Summary of key Django security settings:

SettingPurpose
SECURE_SSL_REDIRECTRedirect HTTP to HTTPS
SESSION_COOKIE_SECURESend session cookies only over HTTPS
CSRF_COOKIE_SECURESend CSRF cookies only over HTTPS
SECURE_HSTS_SECONDSEnable HTTP Strict Transport Security
SECURE_BROWSER_XSS_FILTEREnable browser XSS filtering
SECURE_CONTENT_TYPE_NOSNIFFPrevent MIME type sniffing
DEBUGMust be False in production
ALLOWED_HOSTSRestrict allowed host/domain names
SecurityMiddlewareAdds security headers automatically

Key Takeaways

Always set DEBUG = False and configure ALLOWED_HOSTS in production.
Use SecurityMiddleware and enable SECURE_SSL_REDIRECT to enforce HTTPS.
Set SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to True to protect cookies.
Enable HTTP Strict Transport Security with SECURE_HSTS_SECONDS.
Regularly update Django and dependencies to patch security vulnerabilities.