Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 77 ยท Authentication and Security

Security in Django

See how Django defends against CSRF, XSS, SQL injection and clickjacking, which SECURE_* settings to turn on, and how to run the check --deploy checklist.

Django was built with security in mind: its defaults block the most common web attacks, as long as you use the framework the way it is meant to be used. Most real-world Django security problems come from switching a protection off (|safe, csrf_exempt, raw SQL built with f-strings) or from a leaky deployment (DEBUG=True, a committed secret key).

In this lesson you will watch each defense work and see exactly how it is bypassed by mistake. The examples cover CSRF, XSS, SQL injection and clickjacking, then move to the HTTPS-related SECURE_* settings, ALLOWED_HOSTS, the check --deploy checklist and how to handle secrets.

Security is layered. Django's protections reduce risk a great deal, but they do not replace strong passwords, up-to-date dependencies, backups or a careful look at what your own code exposes.

The big four attacks at a glance

flowchart LR
    R["Attack"] --> C["CSRF<br/>forged request from another site"]
    R --> X["XSS<br/>script injected into your page"]
    R --> S["SQL injection<br/>input becomes SQL"]
    R --> F["Clickjacking<br/>your page hidden in a frame"]
    C --> C2["CsrfViewMiddleware<br/>+ csrf_token"]
    X --> X2["Template autoescaping"]
    S --> S2["ORM and query parameters"]
    F --> F2["XFrameOptionsMiddleware"]

Each attack has a matching built-in defense; the sections below show them working and show how to break them by accident.

CSRF: cross-site request forgery

Browsers attach your cookies to every request to your site, even one triggered by a hidden form on a malicious page. If a logged-in user visits that page, the forged POST would run with their session. Django stops this by requiring every unsafe request (POST, PUT, PATCH, DELETE) to carry a secret token that a foreign site cannot read: the CsrfViewMiddleware sets a csrftoken cookie and compares it with the {% csrf_token %} field in the form (or an X-CSRFToken header for JavaScript requests). A missing or wrong token produces a 403.

Only exempt a view with @csrf_exempt when it is called by machines that cannot hold a token (webhooks), and authenticate those requests another way, such as a signature. Behind a proxy or on another domain, list your origins in CSRF_TRUSTED_ORIGINS.

Clickjacking and security headers

Clickjacking loads your page in an invisible <iframe> on a hostile site so that a victim unknowingly clicks your buttons. XFrameOptionsMiddleware adds an X-Frame-Options header (default DENY in new projects) that tells browsers not to frame the page. Use @xframe_options_sameorigin on a view that your own site may embed.

SecurityMiddleware adds more headers and the HTTPS redirect: SECURE_SSL_REDIRECT, SECURE_HSTS_SECONDS (HTTP Strict Transport Security), SECURE_CONTENT_TYPE_NOSNIFF and SECURE_REFERRER_POLICY. Django 6.0 and later also supports a Content Security Policy through its own middleware and SECURE_CSP settings; check the release notes of your version.

Python CSRF tokens, security headers and framing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first POST is rejected with 403 even though the user would be "logged in" in a real browser, because the forged request cannot know the token. Both ways of sending the token (form field and header) succeed. Note also what the plain-HTTP request did: SECURE_SSL_REDIRECT answered with a redirect to HTTPS.

XSS: cross-site scripting

XSS happens when text typed by one user is placed into a page as HTML, so a comment containing <script> runs in the browsers of everyone who views it. Django templates escape every variable by default: < becomes &lt;, quotes become &quot;, and the browser shows the text instead of running it.

You can switch the protection off by accident. Avoid these unless the content is truly trusted:

  • the |safe filter and {% autoescape off %}
  • mark_safe() on text that includes user input
  • building HTML with string formatting. Use format_html() instead: it escapes the arguments and trusts only the template string.

Also be careful where a value lands. Escaping protects HTML text, but href="{{ url }}" still accepts javascript: links, so validate user-supplied URLs; use |urlencode inside query strings; and pass data to JavaScript with json_script rather than pasting it into a <script> block.

SQL injection

SQL injection happens when user input becomes part of the SQL text. The ORM never does that: it sends the SQL and the values separately, so a value can never change the meaning of a query. Trouble starts when you write SQL yourself. Model.objects.raw(), connection.cursor().execute(), extra() and RawSQL all accept a parameter list (%s placeholders); build the string with an f-string or % formatting and you have created the vulnerability.

Python Autoescaping and SQL injection side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first block shows the same attack string rendered three ways. Only the default and format_html outputs are inert text; |safe hands the script to the browser. In the second block the f-string query was fooled by ' OR '1'='1 and leaked every row, while the parameterized version treated the whole string as one harmless value that matched nobody.

HTTPS and the SECURE_* settings

Run production only over HTTPS. The settings that enforce it:

Setting Value in production Purpose
SECURE_SSL_REDIRECT True Redirect HTTP to HTTPS
SECURE_HSTS_SECONDS Start small (3600), then 31536000 Tell browsers to use HTTPS only
SECURE_HSTS_INCLUDE_SUBDOMAINS, SECURE_HSTS_PRELOAD True once sure Extend HSTS to subdomains and preload lists
SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE True Cookies travel only over HTTPS
SECURE_PROXY_SSL_HEADER ("HTTP_X_FORWARDED_PROTO", "https") Needed behind a proxy that terminates TLS (set only if the proxy always overwrites that header)
ALLOWED_HOSTS ["example.com"] Reject requests with a forged Host header
DEBUG False Never show debug pages or settings to the world

ALLOWED_HOSTS protects against host-header attacks, such as poisoned password-reset links. With DEBUG=False Django refuses any request whose host is not on the list. Be careful with HSTS: once a browser has seen the header it will refuse plain HTTP for that long, so raise the value gradually.

The deployment checklist

Django can audit your settings for you. python manage.py check --deploy runs extra checks and prints warnings with ids such as security.W018. Run it in your production configuration (or in CI) until it is clean. The example below runs the same checks in-process, first against an insecure setup and then against a hardened one.

Python Running the deployment checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The list of ids empties out as each setting is fixed. The SECRET_KEY used in the hardened block is only a throwaway for the demo (the checker wants a long, varied key); real keys must never appear in code or on a web page.

Handling secrets

SECRET_KEY signs sessions, password-reset links, signed cookies and more. Anyone who knows it can forge those values. Database passwords, API tokens and email credentials are secrets too. Rules that work:

  • Never commit secrets to version control. Read them from environment variables (or a secrets manager) in settings.py.
  • Use a different key per environment, and generate it with django.core.management.utils.get_random_secret_key().
  • Keep .env files out of Git (.gitignore) and out of Docker images.
  • If a key leaks, rotate it. Django supports SECRET_KEY_FALLBACKS so old signed values keep working while you move to a new key.
Python
# settings.py (read-only sketch)
import os

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]  # crash early if it is missing
DEBUG = os.environ.get("DJANGO_DEBUG") == "1"  # off unless explicitly enabled
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")

Finally, keep Django and your dependencies up to date. Security releases are announced in advance, and staying on a supported (preferably LTS) version is one of the cheapest defenses you have. Deploying Django puts these settings into a full production setup.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A POST request to a Django view fails with 403 because no CSRF token was sent. Which is the correct fix for a normal HTML form?

    The token proves that the request came from your own page. @csrf_exempt and removing the middleware remove the protection. Reserve exemptions for machine-to-machine endpoints that use another form of authentication.
  2. 2. Which of these re-opens an XSS hole in a Django template?

    |safe tells the template engine not to escape the value, so a script tag in user input reaches the browser as real HTML. The other filters keep autoescaping on.
  3. 3. Why is Account.objects.filter(owner=user_input) safe from SQL injection?

    The ORM builds SQL with placeholders and passes the values separately, so input cannot change the structure of the query. The same holds for raw() and cursor.execute() when you use %s parameters instead of string formatting.
  4. 4. What does check --deploy do?

    python manage.py check --deploy audits settings such as DEBUG, ALLOWED_HOSTS, SECRET_KEY, HSTS and secure cookies, and prints warnings with ids like security.W018.
  5. 5. Where should SECRET_KEY live in a production project?

    Anyone who obtains the key can forge signed values such as sessions and reset links, so it must stay out of version control and be different per environment.

Summary

  • CSRF: keep CsrfViewMiddleware on, put {% csrf_token %} in forms, and exempt only machine-to-machine endpoints.
  • XSS: autoescaping protects you until you use |safe, mark_safe or string-built HTML; prefer format_html and json_script.
  • SQL injection: use the ORM, and %s parameters whenever you write raw SQL; never format input into SQL text.
  • Clickjacking and headers: XFrameOptionsMiddleware and SecurityMiddleware add X-Frame-Options, HSTS, nosniff and a referrer policy.
  • Production needs DEBUG=False, a strict ALLOWED_HOSTS, HTTPS redirect, HSTS (raised gradually) and secure cookies.
  • Run check --deploy until it is clean, keep secrets in the environment, and keep Django updated.

Next up: Middleware.