EthicsComputerCourses
Join training +91 90532 10052

Security Checklist

Django + React · Lesson 16 of 20 Intermediate 13 min read Updated

By the end of this lesson BookShelf will pass Django's own deployment check with no issues, force HTTPS, limit how fast anyone can call the API, and have a test that proves no anonymous visitor can change data. You will also scan both halves for known vulnerable packages and plan how secrets live and change on a server.

What you should know first: Authentication: Sessions vs JWT, CORS & CSRF Between Django and React, Media Files & Uploads and Testing Django + React. The Django course's Security: CSRF, XSS & Settings explains the attacks themselves. Versions checked: Django 6.1.3, Django REST Framework 3.18.3, django-cors-headers 4.9.0, Pillow 13.0.0, pip-audit 2.10.1 and npm 10.9.2.

The checklist at a glance

Before a train leaves the yard at Lucknow, a team walks its length with a checklist: brakes, couplings, doors, lights. Nobody trusts memory. A web app deserves the same walk before it faces the internet.

AreaThe riskBookShelf's answer
SettingsDEBUG on, weak cookies, no HTTPScheck --deploy with no issues
TransportPasswords read on public Wi-FiHTTPS redirect and HSTS
Cross-site requestsAnother site posts as your userCSRF, SameSite cookies, empty CORS list
AbusePassword guessing, scrapingThrottles in a shared cache
PermissionsOne forgotten check opens the databaseAn audit command and a test
UploadsFake images, huge imagesPillow checks and size limits
DependenciesA known hole in a librarypip-audit and npm audit
SecretsA key leaked in Git.env outside Git, key rotation

Step 1: ask Django what is unsafe

Django can inspect its own settings. Run the check the way the server will run it, with DEBUG off (real environment variables win over .env):

Terminal
DJANGO_DEBUG=False python manage.py check --deploy
Output
SystemCheckError: System check identified some issues:

ERRORS:
?: (mail.E001) Your MAILERS setting uses a development-only email backend in the 'default' entry (django.core.mail.backends.console.EmailBackend).
	HINT: Use a production-ready email backend, such as the SMTP backend, otherwise email will not be sent.

WARNINGS:
?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. ...
?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. ...

System check identified 3 issues (0 silenced).

(Long warning texts are cut at ....) With DEBUG on, the same command also lists W012, W016 and W018: cookies without Secure and DEBUG itself. Our settings already tie SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to not DEBUG, so those vanish in production mode. The error comes from the MAILERS setting that Django 6.1's startproject generated: it prints emails to the console, which is useless on a server.

Step 2: HTTPS, HSTS and real email

Add this block to config/settings.py, below CSRF_TRUSTED_ORIGINS:

Python
def env_bool(name, default="False"):
    """True only when the variable is exactly 'True'."""
    return os.environ.get(name, default) == "True"


# Old keys still accepted for signed data while you rotate SECRET_KEY
SECRET_KEY_FALLBACKS = env_list("DJANGO_SECRET_KEY_FALLBACKS")

if not DEBUG:
    # Production: Nginx speaks HTTPS to browsers and plain HTTP to Gunicorn.
    # It sets X-Forwarded-Proto, which tells Django the visit was HTTPS.
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
    SECURE_SSL_REDIRECT = True
    # HSTS: start small (3600 = one hour); raise to a year once HTTPS is stable
    SECURE_HSTS_SECONDS = int(os.environ.get("DJANGO_HSTS_SECONDS", "3600"))
    SECURE_HSTS_INCLUDE_SUBDOMAINS = env_bool("DJANGO_HSTS_SUBDOMAINS")
    SECURE_HSTS_PRELOAD = env_bool("DJANGO_HSTS_PRELOAD")

And replace the MAILERS block at the end of the file:

Python
if DEBUG:
    MAILERS = {"default": {"BACKEND": "django.core.mail.backends.console.EmailBackend"}}
else:
    MAILERS = {
        "default": {
            "BACKEND": "django.core.mail.backends.smtp.EmailBackend",
            "OPTIONS": {
                "host": os.environ.get("DJANGO_EMAIL_HOST", "localhost"),
                "port": int(os.environ.get("DJANGO_EMAIL_PORT", "587")),
                "username": os.environ.get("DJANGO_EMAIL_USER", ""),
                "password": os.environ.get("DJANGO_EMAIL_PASSWORD", ""),
                "use_tls": True,
            },
        }
    }
  • SECURE_PROXY_SSL_HEADER. Gunicorn receives plain HTTP from Nginx, so Django would believe every visit is insecure. Nginx adds X-Forwarded-Proto: https, and this line tells Django to trust it. Only set it when Gunicorn listens on 127.0.0.1, so the header can only come from your own Nginx.
  • SECURE_SSL_REDIRECT answers any http:// request with a 301 to https://.
  • HSTS (HTTP Strict Transport Security) tells the browser "use only HTTPS here for this many seconds". A browser that has seen it will not even try plain HTTP. It cannot be taken back early, so you start with one hour.

Run the check again and two warnings remain:

Output
WARNINGS:
?: (security.W005) You have not set the SECURE_HSTS_INCLUDE_SUBDOMAINS setting to True. ...
?: (security.W021) You have not set the SECURE_HSTS_PRELOAD setting to True. ...

System check identified 2 issues (0 silenced).

These are decisions, not bugs. After a week of HTTPS with no trouble on the domain and every subdomain, set DJANGO_HSTS_SECONDS=31536000 (one year), DJANGO_HSTS_SUBDOMAINS=True and DJANGO_HSTS_PRELOAD=True. The browser preload list at hstspreload.org needs exactly those. Then:

Output
System check identified no issues (0 silenced).

Now test it. We started runserver with DJANGO_DEBUG=False and DJANGO_ALLOWED_HOSTS=bookshelf.example.in, then sent three requests: plain HTTP, HTTP "from Nginx" with the HTTPS header, and a stranger's host name.

Terminal
curl -i http://127.0.0.1:8040/api/health/ -H "Host: bookshelf.example.in"
curl -i http://127.0.0.1:8040/api/health/ -H "Host: bookshelf.example.in" -H "X-Forwarded-Proto: https"
curl -i http://127.0.0.1:8040/api/health/ -H "Host: evil.example" -H "X-Forwarded-Proto: https"
Output
HTTP/1.1 301 Moved Permanently
Location: https://bookshelf.example.in/api/health/

HTTP/1.1 200 OK
Content-Type: application/json
X-Frame-Options: DENY
Strict-Transport-Security: max-age=3600
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
{"status":"ok","app":"BookShelf API"}

HTTP/1.1 400 Bad Request

(Only the useful headers are shown.) The last one is ALLOWED_HOSTS at work. Paste any response's headers into this checker to see which protections are missing:

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const WANTED = {
  "strict-transport-security": "Browsers may still try plain HTTP",
  "x-content-type-options": "Browsers may guess file types (nosniff missing)",
  "x-frame-options": "Other sites can frame your pages (clickjacking)",
  "referrer-policy": "Full URLs may leak to other sites",
};

const sample = `HTTP/1.1 200 OK
Content-Type: application/json
X-Frame-Options: DENY
Strict-Transport-Security: max-age=3600
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin`;

function Checker() {
  const [text, setText] = useState(sample);
  const present = new Set(text.split("\n").map((line) => line.split(":")[0].trim().toLowerCase()));
  return (
    <main>
      <textarea rows="8" cols="60" value={text} onChange={(e) => setText(e.target.value)} aria-label="Response headers" />
      <ul>
        {Object.entries(WANTED).map(([name, risk]) => (
          <li key={name} style={{ color: present.has(name) ? "green" : "#b00020" }}>
            {present.has(name) ? "OK" : "MISSING"} {name}{present.has(name) ? "" : `: ${risk}`}
          </li>
        ))}
      </ul>
    </main>
  );
}

createRoot(document.getElementById("root")).render(<Checker />);

All four lines start green. Delete the HSTS line and it turns red with the reason.

Step 3: review CSRF, CORS and cookies

BookShelf runs on one origin in production, so both cross-origin lists must be empty. In production mode, python manage.py shell -c printed the real values:

Output
[] []
True False Lax

That is CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS empty, the session cookie HttpOnly, the CSRF cookie readable by our React code (it must copy it into X-CSRFToken) and SameSite Lax. The cookies Django sent over the proxied HTTPS request also carried Secure. A login from a page on another origin is refused even with a valid token:

Output
{"detail":"CSRF Failed: Origin checking failed - https://evil.example does not match any trusted origins."}

The same request with Origin: https://bookshelf.example.in got past CSRF and reached the password check. Keep three rules: no @csrf_exempt, never CORS_ALLOW_ALL_ORIGINS with credentials, and fill the two lists only if you truly split origins.

Step 4: throttle every request, in a shared cache

The login view already allows five attempts a minute. Now give every request a ceiling. In REST_FRAMEWORK, add the default classes and rates, and tell DRF how many proxies stand in front:

Python
"DEFAULT_THROTTLE_CLASSES": [
    "rest_framework.throttling.AnonRateThrottle",
    "rest_framework.throttling.UserRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {
    "anon": "120/minute",
    "user": "300/minute",
    "login": "5/minute",  # ScopedRateThrottle on the login view
},
# How many proxies (Nginx = 1) add themselves to X-Forwarded-For
"NUM_PROXIES": int(os.environ.get("DJANGO_NUM_PROXIES", "0")),

Throttles count in Django's cache. The default cache lives inside one process, and Gunicorn runs several, so with three workers "5 a minute" quietly becomes 15. Use one cache for all of them. Add this above REST_FRAMEWORK, then run python manage.py createcachetable once:

Python
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.db.DatabaseCache",
        "LOCATION": "bookshelf_cache",
    }
}

A database table is slower than Redis, but it needs no new service, which suits a small site. Tests that never touch the database would now fail, so add a memory cache to config/test_settings.py: CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}.

Why NUM_PROXIES? DRF identifies a visitor by address. When it is not set and an X-Forwarded-For header exists, DRF uses the whole header as the identity, and the client writes that header. We tested it against runserver: seven wrong passwords, each with a different invented X-Forwarded-For, then seven without it:

Output
400 400 400 400 400 400 400
400 400 400 400 400 429 429

The fake header made the attacker a new person every time. Behind Nginx, which appends the real address, DJANGO_NUM_PROXIES=1 makes DRF read only the last entry. With headers like 10.0.0.1, 203.0.113.7 the result became 400 400 400 400 400 429 429. Try the rule yourself:

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

// Same logic as DRF's BaseThrottle.get_ident()
function ident(remoteAddr, xff, numProxies) {
  if (numProxies !== null) {
    if (numProxies === 0 || !xff) return remoteAddr;
    const addrs = xff.split(",");
    return addrs[addrs.length - Math.min(numProxies, addrs.length)].trim();
  }
  return xff ? xff.replace(/\s/g, "") : remoteAddr;
}

function Demo() {
  const [xff, setXff] = useState("10.0.0.7, 203.0.113.7");
  return (
    <main>
      <p>REMOTE_ADDR (Nginx): 127.0.0.1</p>
      <label>X-Forwarded-For <input size="30" value={xff} onChange={(e) => setXff(e.target.value)} /></label>
      <ul>
        <li>NUM_PROXIES unset: <code>{ident("127.0.0.1", xff, null)}</code></li>
        <li>NUM_PROXIES = 1: <code>{ident("127.0.0.1", xff, 1)}</code></li>
      </ul>
    </main>
  );
}

createRoot(document.getElementById("root")).render(<Demo />);

Change 10.0.0.7 to anything. The first identity changes with it; the second stays 203.0.113.7, the address Nginx saw.

Step 5: audit every permission

A permission you forgot is invisible in normal testing. Make the list visible. Create books/management/commands/audit_permissions.py (with empty __init__.py files in management and commands):

Python
from django.core.management.base import BaseCommand
from django.urls import URLResolver, get_resolver


def walk(patterns, prefix=""):
    for p in patterns:
        if isinstance(p, URLResolver):
            yield from walk(p.url_patterns, prefix + str(p.pattern))
        else:
            yield prefix + str(p.pattern), p.callback


class Command(BaseCommand):
    help = "List every DRF URL with the permission classes that guard it."

    def handle(self, *args, **options):
        for route, view in walk(get_resolver().url_patterns):
            cls = getattr(view, "cls", None)  # set on every DRF view
            if cls is None or "format" in route:
                continue
            actions = getattr(view, "actions", None)  # ViewSets: {"get": "list", ...}
            names = actions or [m for m in cls.http_method_names if hasattr(cls, m)]
            methods = ",".join(m.upper() for m in names if m not in ("head", "options"))
            perms = ", ".join(p.__name__ for p in cls.permission_classes)
            path = route.replace("(?P<pk>[^/.]+)", "<pk>").replace("^", "").replace("$", "")
            self.stdout.write(f"/{path:25} {methods:21} {perms}")
Terminal
python manage.py audit_permissions
Output
/api/health/               GET                   IsAuthenticatedOrReadOnly
/api/auth/csrf/            GET                   AllowAny
/api/auth/login/           POST                  AllowAny
/api/auth/logout/          POST                  AllowAny
/api/auth/me/              GET                   IsAuthenticated
/api/reading-time/         POST                  AllowAny
/api/authors/              GET                   IsAuthenticatedOrReadOnly
/api/authors/<pk>/         GET                   IsAuthenticatedOrReadOnly
/api/books/                GET,POST              IsStaffOrReadOnly
/api/books/top/            GET                   IsStaffOrReadOnly
/api/books/<pk>/           GET,PUT,PATCH,DELETE  IsStaffOrReadOnly
/api/books/<pk>/cover/     POST,DELETE           IsStaffOrReadOnly
/api/reviews/              GET,POST              IsAuthenticatedOrReadOnly, IsReviewerOrReadOnly
/api/reviews/<pk>/         GET,PUT,PATCH,DELETE  IsAuthenticatedOrReadOnly, IsReviewerOrReadOnly
/api/                      GET                   IsAuthenticatedOrReadOnly

Read every AllowAny and ask "why?". Here each has a reason: the CSRF cookie, login and logout must work for strangers, and the calculator touches no data. Every write needs a login or staff. Now lock that in with books/test_security.py:

Python
import pytest
from rest_framework.test import APIClient

# Every URL and method that changes data. Anonymous visitors must get 403 on all of them.
UNSAFE = [
    ("post", "/api/authors/"),
    ("post", "/api/books/"),
    ("patch", "/api/books/1/"),
    ("delete", "/api/books/1/"),
    ("post", "/api/books/1/cover/"),
    ("post", "/api/reviews/"),
    ("patch", "/api/reviews/1/"),
    ("delete", "/api/reviews/1/"),
]


@pytest.mark.django_db
@pytest.mark.parametrize(("method", "url"), UNSAFE)
def test_anonymous_visitor_cannot_change_anything(method, url):
    response = getattr(APIClient(), method)(url, {}, format="json")
    assert response.status_code == 403

When a later lesson adds an endpoint, add its unsafe methods to the list. The admin is not in the audit because it is not DRF; protect it with strong staff passwords and give is_staff to as few people as possible.

Step 6: uploads, once more

Media Files & Uploads checks format, bytes and pixels. One more attack hides in small files: a decompression bomb, an image that is tiny on disk but huge in memory. Pillow refuses images above 178,956,970 pixels (twice its MAX_IMAGE_PIXELS of 89,478,485). The same test file adds a test that uploads a 48 KB black PNG of 20,000 x 20,000 pixels as staff and expects 400 with Django's "Upload a valid image" message. It passed. The full run:

Output
accounts\tests.py ....                                                   [ 13%]
books\test_reading_time.py .                                             [ 17%]
books\test_security.py .........                                         [ 48%]
books\tests.py ............                                              [ 89%]
books\test_reading_time.py ...                                           [100%]

============================= 29 passed in 8.90s ==============================

On the server, remember that Nginx's client_max_body_size is 1 MB by default. Set it a little above the 2 MB cover limit, and serve /media/ with nosniff from a folder where nothing can run as code. The next lesson does both.

Step 7: audit your dependencies

Your code can be perfect and a library can still have a published hole. pip-audit compares your pinned packages with the Python Packaging Advisory Database. Keep it out of the project's own venv, so it never lands in requirements.txt:

Terminal
python -m venv ../audit-venv
../audit-venv/Scripts/python -m pip install pip-audit
../audit-venv/Scripts/pip-audit -r requirements.txt
Output
No known vulnerabilities found

To see what a finding looks like, we audited a file pinning the old Django 6.0.1 (with --disable-pip --no-deps, which skips installing it):

Output
Found 51 known vulnerabilities in 1 package
Name   Version ID              Fix Versions
------ ------- --------------- -------------------
django 6.0.1   PYSEC-2026-42   4.2.28,5.2.11,6.0.2
django 6.0.1   PYSEC-2026-44   4.2.28,5.2.11,6.0.2

Each row names an advisory and the versions that fix it. The cure is almost always "upgrade within your series": Django publishes security fixes as point releases such as 6.1.3. For the front end, npm has the same tool built in. Run it in frontend:

Terminal
npm audit
npm audit --omit=dev
Output
found 0 vulnerabilities
found 0 vulnerabilities

--omit=dev checks only what ships to browsers; a hole in Vitest matters less than one in React Router. Run both audits in CI on every push, and let GitHub's Dependabot open upgrade pull requests.

Step 8: secrets on the server

  • One .env per server, never in Git. git check-ignore -v backend/.env must print a rule. On Linux, make the file readable only by the app's user: chmod 600 .env.
  • A new SECRET_KEY for production. Generate it on the server; never copy your laptop's key.
  • Rotate without logging everyone out. Put the new key in DJANGO_SECRET_KEY and the old one in DJANGO_SECRET_KEY_FALLBACKS. Django still accepts sessions signed with the old key; remove it a week later.
  • A leaked key is a stolen key. Deleting it from Git does not remove it from history. Rotate it, and change the database password too.
  • Nothing secret in VITE_ variables. They are copied into the public JavaScript bundle.

Common mistakes

  • Running check --deploy with DEBUG on. You see the wrong list. Run it with production settings.
  • SECURE_SSL_REDIRECT without SECURE_PROXY_SSL_HEADER. Every request redirects to HTTPS again, for ever.
  • Throttles in a per-process cache. Each Gunicorn worker counts separately.
  • Trusting X-Forwarded-For blindly. Set NUM_PROXIES to the real number of proxies, and keep Gunicorn on 127.0.0.1.
  • HSTS for a year on day one. A broken certificate then locks visitors out with no way back.

Interview questions

1. What does python manage.py check --deploy do?

It runs Django's system checks plus extra checks for production: DEBUG, ALLOWED_HOSTS, the secret key, HTTPS redirects, HSTS, secure cookies and, in Django 6.1, the email backend. Run it with the real production settings before every release.

2. Why does Django need SECURE_PROXY_SSL_HEADER behind Nginx?

Nginx ends the HTTPS connection and talks plain HTTP to Gunicorn, so request.is_secure() would be false. The setting tells Django to trust Nginx's X-Forwarded-Proto header. It is only safe when clients cannot reach Gunicorn directly.

3. How can an attacker get around a rate limit, and how do you stop it?

By changing whatever the limit uses as identity, for example a forged X-Forwarded-For header. In DRF, set NUM_PROXIES so only the address added by your own proxy counts, and store throttle counts in a cache shared by all workers.

4. How do you rotate Django's SECRET_KEY safely?

Set the new key as SECRET_KEY and move the old one into SECRET_KEY_FALLBACKS. Existing sessions and signed links keep working; when you remove the old key later, they expire.

Key points

  • Run check --deploy with production settings and fix every line, including Django 6.1's email error.
  • Behind Nginx, set SECURE_PROXY_SSL_HEADER, redirect to HTTPS and raise HSTS step by step.
  • One origin means empty CORS and CSRF trusted lists; keep CSRF on and cookies Secure.
  • Throttle every request, keep counts in a shared cache and set NUM_PROXIES.
  • Audit permissions with a command and lock them in with a test of anonymous writes.
  • Run pip-audit and npm audit in CI, and keep secrets in a protected .env with key rotation.

Exercise

Readers may post or edit at most 20 reviews an hour, but reading reviews must stay limited only by the normal rates. Add a scoped throttle that applies to the unsafe methods of ReviewViewSet only, and a pytest test that makes 21 writes as Kabir and expects the last one to get 429 while a GET /api/reviews/ still returns 200.

Show solution
Python
# config/settings.py, in DEFAULT_THROTTLE_RATES
"review-writes": "20/hour",

# books/views.py (import ScopedRateThrottle from rest_framework.throttling)
class ReviewViewSet(viewsets.ModelViewSet):
    # ... serializer_class, permission_classes and get_queryset as before ...
    throttle_scope = "review-writes"

    def get_throttles(self):
        throttles = super().get_throttles()  # the anon and user limits still apply
        if self.request.method not in permissions.SAFE_METHODS:
            throttles.append(ScopedRateThrottle())  # extra limit for writes only
        return throttles
Python
# books/test_security.py
@pytest.mark.django_db
def test_21st_review_write_in_an_hour_is_throttled():
    cache.clear()
    book = Book.objects.create(title="Godaan", author=Author.objects.create(name="Premchand"), published_year=1936)
    client = APIClient()
    client.force_authenticate(User.objects.create_user("kabir", password="x"))
    codes = [client.post("/api/reviews/", {"book": book.id, "rating": 4}, format="json").status_code for _ in range(21)]
    assert codes[0] == 201
    assert codes[-1] == 429
    assert client.get("/api/reviews/").status_code == 200

Failed writes count too: requests 2 to 20 get 400 for the duplicate review, and the 21st is throttled before validation. The test passed in our project. Import cache, User, Author and Book at the top of the file.

Quick Quiz

1. Why must throttle counts live in a shared cache in production?

2. A browser receives Strict-Transport-Security: max-age=31536000. What happens next?

3. What did DJANGO_NUM_PROXIES=1 change in the login test?

4. Which tool checks the front end's packages for known vulnerabilities?

Learn Django + React with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call