ZetCode

Django security

last modified November 22, 2026 Python 3.15

Django protects an application against many attacks out of the box. Templates escape variables, the ORM passes values to the database separately from the SQL, the CSRF middleware rejects forged forms, and the clickjacking middleware forbids other sites to put our pages into frames. Each protection can be switched off with one careless line, and some problems are outside of what a framework can see: Django does not know which user may read which row, or which form fields a user may set. In this article we build a small notes application, open a hole in it in each section, attack it with curl or a short script, and close the hole again. The examples use Django 6.1 and Python 3.15.

Settings for production, such as DEBUG, ALLOWED_HOSTS, the secret key, HTTPS redirects, and HSTS, and the command check --deploy are covered in Django settings and environment; password hashing and validation in Django authentication; and the Content Security Policy in Django Content Security Policy.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, generate the project with the configuration package config, start the app notes, and create the folder demos for demo scripts.

$ mkdir notebook
$ cd notebook
$ uv init --bare
$ uv add django
$ uv run django-admin startproject config .
$ uv run python manage.py startapp notes
$ mkdir demos

The trailing dot in startproject config . creates manage.py and the config package in the current directory. We add the new app to INSTALLED_APPS in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'notes',
]

The listings in this article are of two kinds. A listing with a solid blue border and the label Project file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed amber border and the label Demo script is a small helper in the demos folder; it sets up Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are not part of the application; we run one from the project directory with uv run python -m demos.name.

The MIDDLEWARE setting generated by startproject already contains the security related middleware, and we keep it unchanged. SecurityMiddleware adds security headers, CsrfViewMiddleware checks forms, and XFrameOptionsMiddleware protects against clickjacking; we meet the last two later in the article.

config/settings.py
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',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

The order matters: SecurityMiddleware comes first, so that its redirects and headers apply to every response, and the CSRF check runs after the session middleware and before the views.

The notes model

A note belongs to a user. Private notes are visible only to their owner, public notes are listed on the home page for everybody. The method get_absolute_url() returns the URL of the note's page, which redirect() uses later.

notes/models.py
from django.conf import settings
from django.db import models
from django.urls import reverse


class Note(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    body = models.TextField()
    public = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('note-detail', args=[self.pk])

We create the migration and apply it. The output of migrate is shortened to the line of our app; the other lines apply the migrations of Django's own apps.

$ uv run python manage.py makemigrations notes
Migrations for 'notes':
  notes/migrations/0001_initial.py
    + Create model Note
$ uv run python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, notes, sessions
Running migrations:
  Applying notes.0001_initial... OK

Sample data

The seed script creates two users, alice and bob, and five notes. Bob is the attacker of this article; his public note already contains a script element, which would run in the browser of anybody who reads the note if the page included it as HTML.

demos/seed.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from django.contrib.auth.models import User

from notes.models import Note

alice = User.objects.create_user('alice', password='alice-secret-1')
bob = User.objects.create_user('bob', password='bob-secret-1')

Note.objects.create(owner=alice, title='Shopping list', body='Milk, bread, apples')
Note.objects.create(owner=alice, title='Wi-Fi password', body='correct horse battery staple')
Note.objects.create(owner=alice, title='Book club', public=True,
                    body='Next meeting on Friday.\nBring the second volume.')
Note.objects.create(owner=bob, title='Holiday plans', body='Two weeks in the mountains')
Note.objects.create(owner=bob, title='Hello from Bob', public=True,
                    body='Nice to meet you!<script>alert(document.cookie)</script>')

for note in Note.objects.order_by('pk'):
    state = 'public' if note.public else 'private'
    print(note.pk, note.owner, state, note.title)

The users are created with create_user(), which hashes the passwords. The \n in the body of the book club note is a line break, which we need in a moment.

$ uv run python -m demos.seed
1 alice private Shopping list
2 alice private Wi-Fi password
3 alice public Book club
4 bob private Holiday plans
5 bob public Hello from Bob

Auto-escaping

Cross-site scripting (XSS) is an attack in which the attacker gets their JavaScript code into a page that another user opens. The code runs with the rights of the victim on our site: it can read the page, send requests in the victim's name, and read cookies that are not marked HttpOnly. The home page lists the public notes, so it shows text written by other users.

notes/views.py
from django.shortcuts import render

from .models import Note


def home(request):
    notes = Note.objects.filter(public=True).select_related('owner')
    return render(request, 'notes/list.html', {'notes': notes})

The view selects the public notes with their owners and renders them with a template. The app's URLconf maps the root URL to it.

notes/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

The project URLconf includes the URLs of the app, the admin, and the authentication views of django.contrib.auth, which provide the login page.

config/urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('', include('notes.urls')),
]

The template prints the title, the body, and the owner of each note.

notes/templates/notes/list.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Notes</title>
</head>
<body>
  {% for note in notes %}
    <article>
      <h2>{{ note.title }}</h2>
      <p>{{ note.body }}</p>
      <footer>by {{ note.owner }}</footer>
    </article>
  {% endfor %}
</body>
</html>

Django's template engine escapes every variable: the characters <, >, &, ', and " are replaced with HTML entities, so the browser shows them as text instead of reading them as markup. We start the development server with uv run python manage.py runserver and fetch the page with curl in another terminal; grep keeps the lines with the titles and the bodies.

Bob's script element arrives as harmless text. Auto-escaping is the reason why XSS is rare in Django applications: we do not have to remember to escape, we have to remember not to switch the escaping off.

$ curl -s localhost:8000/ | grep -E '<h2>|<p>'
      <h2>Hello from Bob</h2>
      <p>Nice to meet you!&lt;script&gt;alert(document.cookie)&lt;/script&gt;</p>
      <h2>Book club</h2>
      <p>Next meeting on Friday.

Turning escaping off

The body of the book club note has two lines, but HTML ignores the line break, so the page shows one line. A developer who wants to keep the line break may write the HTML into the notes and mark the body as safe. We change the paragraph in list.html.

notes/templates/notes/list.html
      <p>{{ note.body|safe }}</p>

The filter safe tells the template engine that the value is trusted HTML that must be printed as it is. The same happens with {% autoescape off %} and with strings passed through mark_safe() in Python code. The development server picks up the changed template, and we fetch the page again.

Now Bob's script is a real script element in the page, and it runs in the browser of every visitor of the home page; alert(document.cookie) stands for any code that steals data. This is stored XSS: the attack is saved in the database and served to everybody. Only text written by the site's own developers, never text from users, can be marked safe.

$ curl -s localhost:8000/ | grep -E '<h2>|<p>'
      <h2>Hello from Bob</h2>
      <p>Nice to meet you!<script>alert(document.cookie)</script></p>
      <h2>Book club</h2>
      <p>Next meeting on Friday.

Line breaks without safe

The right way to show the line breaks is a filter that escapes the text first and then adds the HTML for the breaks. We change the paragraph again.

notes/templates/notes/list.html
      <p>{{ note.body|linebreaksbr }}</p>

The filter linebreaksbr escapes the value and turns each newline into a br element; linebreaks builds paragraphs. The built-in filters that produce HTML from text, such as urlize and linebreaks, all escape their input; when we pass data to JavaScript, the filter json_script does the same for a script element.

Bob's script is escaped again, and the book club note keeps its line break.

$ curl -s localhost:8000/ | grep -E '<h2>|<p>'
      <h2>Hello from Bob</h2>
      <p>Nice to meet you!&lt;script&gt;alert(document.cookie)&lt;/script&gt;</p>
      <h2>Book club</h2>
      <p>Next meeting on Friday.<br>Bring the second volume.</p>

HTML built in Python

Escaping happens in the template, so HTML that is built in Python code needs the same care. We add a search view, which prints a message with the search term in bold.

notes/views.py

from django.shortcuts import render
from django.utils.safestring import mark_safe

from .models import Note


def home(request):
    notes = Note.objects.filter(public=True).select_related('owner')
    return render(request, 'notes/list.html', {'notes': notes})


def search(request):
    q = request.GET.get('q', '')
    notes = Note.objects.filter(public=True, title__icontains=q).select_related('owner')
    message = mark_safe(f'Found {len(notes)} notes for <b>{q}</b>.')
    return render(request, 'notes/list.html', {'notes': notes, 'q': q, 'message': message})

The message is an f-string with HTML in it. Because the template would escape the b tags, the developer wraps the string in mark_safe(). That marks the whole string as safe, including the search term, which comes from the URL. The template gets a search form and the message.

notes/templates/notes/list.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Notes</title>
</head>
<body>
  <form action="{% url 'search' %}">
    <input name="q" value="{{ q }}">
    <button>Search</button>
  </form>
  {% if message %}<p>{{ message }}</p>{% endif %}
  {% for note in notes %}
    <article>
      <h2>{{ note.title }}</h2>
      <p>{{ note.body|linebreaksbr }}</p>
      <footer>by {{ note.owner }}</footer>
    </article>
  {% endfor %}
</body>
</html>

The search term is printed twice: in the value attribute of the input field and in the message. The URLconf gets the new view.

notes/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('search/', views.search, name='search'),
]

We search for a script element. The -G option makes curl send the --data-urlencode data in the query string, encoded properly.

The value of the input field is escaped by the template, but the message carries the script into the page. This is reflected XSS: the attack is in the URL, and the attacker has to make the victim open a link, for instance in an email. Any page that shows something from the request is a candidate.

$ curl -s -G --data-urlencode 'q=<script>alert(1)</script>' localhost:8000/search/ | grep -E '<input|<p>'
    <input name="q" value="&lt;script&gt;alert(1)&lt;/script&gt;">
  <p>Found 0 notes for <b><script>alert(1)</script></b>.</p>

format_html

The function format_html() works like str.format() but escapes every argument before it puts it into the format string; the format string itself, written by us, is kept as HTML, and the result is marked safe. We replace the mark_safe() import and the message line.

notes/views.py
from django.utils.html import format_html
...
    message = format_html('Found {} notes for <b>{}</b>.', len(notes), q)

Now the search term is escaped in the message too, while the b element stays bold. format_html() is the tool for building small pieces of HTML in views, template tags, and admin methods; mark_safe() belongs only on strings that contain no outside data.

$ curl -s -G --data-urlencode 'q=<script>alert(1)</script>' localhost:8000/search/ | grep -E '<input|<p>'
    <input name="q" value="&lt;script&gt;alert(1)&lt;/script&gt;">
  <p>Found 0 notes for <b>&lt;script&gt;alert(1)&lt;/script&gt;</b>.</p>

SQL injection

In an SQL injection, user input becomes part of an SQL statement and changes its meaning. A query built with the ORM is safe, because Django sends the values to the database separately from the SQL text. Raw SQL is safe only if we do the same. We rewrite the search with raw() and an f-string; such code appears when a query is hard to write with the ORM, or when it is copied from a database console.

notes/views.py
def search(request):
    q = request.GET.get('q', '')
    notes = Note.objects.raw(
        f"SELECT * FROM notes_note WHERE public AND title LIKE '%{q}%' ORDER BY title")
    message = format_html('Results for <b>{}</b>.', q)
    return render(request, 'notes/list.html', {'notes': notes, 'q': q, 'message': message})

The search term is pasted into the SQL between quotes. The message no longer counts the results; it only repeats the term. The first request below is an ordinary search. The second closes the quote, adds a condition that is always true, and comments out the rest of the statement with --; the condition public no longer applies, so the private notes of both users appear. The third request adds a UNION with a query on the user table. The selected columns are arranged to match the columns of notes_note (id, title, body, public, created, owner_id), so the user names appear as titles and the password hashes as bodies.

With one request, an anonymous visitor reads every private note and the password hashes of all users. SQLite runs one statement per call, which stops attacks with ; DROP TABLE, but not this one. Here the attacker could see the result in the page; with blind techniques, data can be extracted even from a page that shows nothing of the query.

$ curl -s -G --data-urlencode 'q=book' localhost:8000/search/ | grep -E '<h2>'
      <h2>Book club</h2>
$ curl -s -G --data-urlencode "q=' OR 1=1 --" localhost:8000/search/ | grep -E '<h2>'
      <h2>Shopping list</h2>
      <h2>Wi-Fi password</h2>
      <h2>Book club</h2>
      <h2>Holiday plans</h2>
      <h2>Hello from Bob</h2>
$ curl -s -G --data-urlencode "q=' UNION SELECT id, username, password, 1, date_joined, id FROM auth_user --" localhost:8000/search/ | grep -E '<h2>|<p>'
  <p>Results for <b>&#x27; UNION SELECT id, username, password, 1, date_joined, id FROM auth_user --</b>.</p>
      <h2>alice</h2>
      <p>pbkdf2_sha256$1500000$VlAjd3T0m0n7BajP0PZOXV$zjql1h7ZQmdNvAJ6ZK2QruVfNhIdlfwMDJVZ3igLbW8=</p>
      <h2>bob</h2>
      <p>pbkdf2_sha256$1500000$q0drxXb02vR1KGIHpzrcL8$QA11HwMiOuBmMg/oIP3fh1x3183n9PQ/qvMYLGOFfUM=</p>
      <h2>Book club</h2>
      <p>Next meeting on Friday.<br>Bring the second volume.</p>
      <h2>Hello from Bob</h2>
      <p>Nice to meet you!&lt;script&gt;alert(document.cookie)&lt;/script&gt;</p>

Query parameters

The fix is to pass the value as a query parameter. The SQL contains a placeholder %s without quotes, and the value goes into the list that is the second argument of raw(). The database driver sends it separately, so it can never become SQL.

notes/views.py
def search(request):
    q = request.GET.get('q', '')
    notes = Note.objects.raw(
        "SELECT * FROM notes_note WHERE public AND title LIKE %s ORDER BY title",
        [f'%{q}%'])
    message = format_html('Results for <b>{}</b>.', q)
    return render(request, 'notes/list.html', {'notes': notes, 'q': q, 'message': message})

The percent signs of the LIKE pattern are now part of the value, not of the SQL. The same rule applies to connection.cursor().execute(), RawSQL, and the extra() method: never format values into the SQL string, not even with % or format(), which look like parameters but are not. Raw SQL and cursors are described in Django raw SQL and transactions.

The ordinary search works as before. The two attacks are searches for strange titles now; they find nothing, and the message shows the escaped term.

$ curl -s -G --data-urlencode 'q=book' localhost:8000/search/ | grep -E '<h2>'
      <h2>Book club</h2>
$ curl -s -G --data-urlencode "q=' OR 1=1 --" localhost:8000/search/ | grep -E '<h2>|<p>'
  <p>Results for <b>&#x27; OR 1=1 --</b>.</p>
$ curl -s -G --data-urlencode "q=' UNION SELECT id, username, password, 1, date_joined, id FROM auth_user --" localhost:8000/search/ | grep -E '<h2>|<p>'
  <p>Results for <b>&#x27; UNION SELECT id, username, password, 1, date_joined, id FROM auth_user --</b>.</p>

Sorting by user input

The ORM protects values, but field names are a different story. We write the search with the ORM again and let the user choose the sort order with the parameter sort, a common feature of lists.

notes/views.py
def search(request):
    q = request.GET.get('q', '')
    order = request.GET.get('sort', 'title')
    notes = (Note.objects.filter(public=True, title__icontains=q)
             .select_related('owner').order_by(order))
    message = format_html('Results for <b>{}</b>.', q)
    return render(request, 'notes/list.html', {'notes': notes, 'q': q, 'message': message})

order_by() accepts any field, including fields of related models written with double underscores. To see what an attacker can do with that, we print the users ordered by their password hashes.

demos/hashes.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from django.contrib.auth.models import User

for user in User.objects.order_by('password'):
    print(user.username, user.password[:30] + '...')

The script prints the beginning of each hash; the salt makes every hash different, so the order of the users depends on the run. The first curl command below sorts the public notes by title. The second sorts them by owner__password: the notes now come in the order of their owners' password hashes, the same order as in the demo. The query does not show any hash, but by comparing orders, for instance with accounts the attacker controls, the hashes can be guessed character by character. An unknown field gives a FieldError and the status 500.

$ uv run python -m demos.hashes
alice pbkdf2_sha256$1500000$VlAjd3T0...
bob pbkdf2_sha256$1500000$q0drxXb0...
$ curl -s 'localhost:8000/search/?sort=title' | grep '<footer>'
      <footer>by alice</footer>
      <footer>by bob</footer>
$ curl -s 'localhost:8000/search/?sort=owner__password' | grep '<footer>'
      <footer>by alice</footer>
      <footer>by bob</footer>
$ curl -s -o /dev/null -w '%{http_code}\n' 'localhost:8000/search/?sort=nothing'
500

An allow-list of sort orders

User input must never name fields directly. We map a few public names to the orderings that we allow.

notes/views.py
SORTS = {'title': 'title', 'new': '-created', 'old': 'created'}


def search(request):
    q = request.GET.get('q', '')
    order = SORTS.get(request.GET.get('sort'), 'title')
    notes = (Note.objects.filter(public=True, title__icontains=q)
             .select_related('owner').order_by(order))
    message = format_html('Results for <b>{}</b>.', q)
    return render(request, 'notes/list.html', {'notes': notes, 'q': q, 'message': message})

The dictionary lookup returns None for any other value, and the view falls back to sorting by title. The same applies to filters built from request data, such as filter(**request.GET), which lets the user filter on any field, password included. Django REST framework's OrderingFilter has the setting ordering_fields for the same reason.

The new order works, and the two unknown values give the default order with the status 200.

$ curl -s 'localhost:8000/search/?sort=new' | grep '<h2>'
      <h2>Hello from Bob</h2>
      <h2>Book club</h2>
$ curl -s 'localhost:8000/search/?sort=owner__password' | grep '<h2>'
      <h2>Book club</h2>
      <h2>Hello from Bob</h2>
$ curl -s -o /dev/null -w '%{http_code}\n' 'localhost:8000/search/?sort=nothing'
200

Broken access control

Most security bugs found in real applications are not injections but missing checks: a page shows data that the current user must not see. We add a page for a single note. It is decorated with login_required, so only logged-in users can open it.

notes/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render
...


@login_required
def note_detail(request, pk):
    note = get_object_or_404(Note, pk=pk)
    return render(request, 'notes/detail.html', {'note': note})

The view loads the note by its primary key from the URL. The template shows the title, the body, and the owner.

notes/templates/notes/detail.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{ note.title }}</title>
</head>
<body>
  <h1>{{ note.title }}</h1>
  <p>{{ note.body|linebreaksbr }}</p>
  <footer>by {{ note.owner }}, {{ note.created|date:'Y-m-d' }}</footer>
</body>
</html>

The URLconf gets a route with the primary key.

notes/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('search/', views.search, name='search'),
    path('notes/<int:pk>/', views.note_detail, name='note-detail'),
]

login_required sends anonymous users to the URL in the LOGIN_URL setting, /accounts/login/ by default, which is served by the LoginView from django.contrib.auth.urls. The view needs a template.

notes/templates/registration/login.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Log in</title>
</head>
<body>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button>Log in</button>
  </form>
</body>
</html>

The demo script logs in as bob with the test client and asks for the notes 1 to 5, as an attacker does who sees the number in the URL of their own note and tries the neighbours. force_login() skips the password check, and SERVER_NAME='localhost' gives the requests a host that is allowed when DEBUG is on.

demos/peek.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


import re

from django.contrib.auth.models import User
from django.test import Client

client = Client(SERVER_NAME='localhost')
client.force_login(User.objects.get(username='bob'))

for pk in range(1, 6):
    response = client.get(f'/notes/{pk}/')
    found = re.search(r'<h1>(.*)</h1>\s*<p>(.*)</p>', response.content.decode())
    print(pk, response.status_code, found.groups() if found else '')

The anonymous curl request is redirected to the login page. The login works, but it does not limit what bob can read: he gets alice's private notes, including the Wi-Fi password. This kind of bug is called insecure direct object reference (IDOR); random UUIDs instead of numbers make the guessing harder, but they do not replace the check.

$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8000/notes/2/
302 http://localhost:8000/accounts/login/?next=/notes/2/
$ uv run python -m demos.peek
1 200 ('Shopping list', 'Milk, bread, apples')
2 200 ('Wi-Fi password', 'correct horse battery staple')
3 200 ('Book club', 'Next meeting on Friday.<br>Bring the second volume.')
4 200 ('Holiday plans', 'Two weeks in the mountains')
5 200 ('Hello from Bob', 'Nice to meet you!&lt;script&gt;alert(document.cookie)&lt;/script&gt;')

Checking the owner

The check belongs into the query: we look for the note only among the notes that the user may see. A small function returns them, so that every view uses the same rule.

notes/views.py
from django.db.models import Q
...


def visible_notes(user):
    return Note.objects.filter(Q(owner=user) | Q(public=True))


@login_required
def note_detail(request, pk):
    note = get_object_or_404(visible_notes(request.user), pk=pk)
    return render(request, 'notes/detail.html', {'note': note})

get_object_or_404() accepts a QuerySet as well as a model. A note that exists but belongs to somebody else gives the status 404, the same as a note that does not exist, so the attacker does not even learn which numbers are taken. The class-based views get the same rule by overriding get_queryset().

Bob still sees his own private note 4 and the two public notes; alice's private notes are not found. The Not Found lines are warnings of the django.request logger, which reports every 404 response on the standard error stream.

$ uv run python -m demos.peek
Not Found: /notes/1/
1 404 
Not Found: /notes/2/
2 404 
3 200 ('Book club', 'Next meeting on Friday.<br>Bring the second volume.')
4 200 ('Holiday plans', 'Two weeks in the mountains')
5 200 ('Hello from Bob', 'Nice to meet you!&lt;script&gt;alert(document.cookie)&lt;/script&gt;')

Mass assignment

The next feature is a form for new notes. A ModelForm with fields = '__all__' takes every editable field of the model, the owner included. The developer does not want the user to choose the owner, so the field gets a hidden widget, and the view fills in the current user as the initial value.

notes/forms.py
from django import forms

from .models import Note


class NoteForm(forms.ModelForm):

    class Meta:
        model = Note
        fields = '__all__'
        widgets = {'owner': forms.HiddenInput}

The view validates the form, saves the note, and redirects to the URL in the next parameter of the query string, so that a link can send the user back to the page they came from; without the parameter it redirects to the new note. redirect() accepts a model instance and calls its get_absolute_url().

notes/views.py
from django.shortcuts import get_object_or_404, redirect, render
...
from .forms import NoteForm
...


@login_required
def note_create(request):
    form = NoteForm(request.POST or None, initial={'owner': request.user})
    if form.is_valid():
        note = form.save()
        return redirect(request.GET.get('next') or note)
    return render(request, 'notes/form.html', {'form': form})

The template renders the form with the CSRF token.

notes/templates/notes/form.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>New note</title>
</head>
<body>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button>Save</button>
  </form>
</body>
</html>

The route goes into the list in notes/urls.py.

notes/urls.py
urlpatterns = [
    ...
    path('notes/new/', views.note_create, name='note-create'),
]

The rendered form shows the problem: the hidden field is still a field, and the browser sends whatever value it has. The demo script posts the form as bob, but with alice's id in owner.

demos/forge.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from django.contrib.auth.models import User
from django.test import Client

from notes.models import Note

alice = User.objects.get(username='alice')
client = Client(SERVER_NAME='localhost')
client.force_login(User.objects.get(username='bob'))

data = {'title': 'I owe Bob 100 euros', 'body': 'Signed, Alice', 'public': 'on',
        'owner': alice.pk}
response = client.post('/notes/new/', data)
print(response.status_code, response['Location'])

note = Note.objects.latest('pk')
print(f'{note.title!r} owned by {note.owner}, public: {note.public}')

The form accepts the value, because the owner is a valid user, and the note is saved as alice's: bob has published a note in her name. Hiding a field changes only what the browser shows; an attacker can send any field with curl or the browser's developer tools. The problem is called mass assignment.

$ uv run python manage.py shell --no-imports -c 'from notes.forms import NoteForm; print(NoteForm().as_p())' | grep -E '<input|<textarea'
    <input type="text" name="title" maxlength="100" required id="id_title">
    <textarea name="body" cols="40" rows="10" required id="id_body">
    <input type="checkbox" name="public" id="id_public">
      <input type="hidden" name="owner" id="id_owner">
$ uv run python -m demos.forge
302 /notes/6/
'I owe Bob 100 euros' owned by alice, public: True

Choosing the fields

A form must list the fields that the user may set, and nothing more. We name the three fields in Meta.fields.

notes/forms.py
from django import forms

from .models import Note


class NoteForm(forms.ModelForm):

    class Meta:
        model = Note
        fields = ['title', 'body', 'public']

The owner is set in the view, from the logged-in user, before the note is saved.

notes/views.py
@login_required
def note_create(request):
    form = NoteForm(request.POST or None)
    if form.is_valid():
        form.instance.owner = request.user
        note = form.save()
        return redirect(request.GET.get('next') or note)
    return render(request, 'notes/form.html', {'form': form})

form.instance is the unsaved model instance that the form fills; we assign the owner and then call save(). Django's documentation recommends fields over exclude and '__all__' for this reason: a field added to the model later is not editable until somebody adds it to the form. The same rule applies to the serializers of Django REST framework.

The forged owner value is ignored; the form does not know the field. The note belongs to bob.

$ uv run python -m demos.forge
302 /notes/7/
'I owe Bob 100 euros' owned by bob, public: True

Open redirects

The next parameter of the form view is taken from the URL without a check. The demo script posts the form with several targets and prints where the response redirects.

demos/redirects.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from urllib.parse import quote

from django.contrib.auth.models import User
from django.test import Client

client = Client(SERVER_NAME='localhost')
client.force_login(User.objects.get(username='bob'))

targets = ['/search/?q=plans', 'https://evil.example/login/', '//evil.example/',
           'http://localhost/search/']
for target in targets:
    response = client.post(f'/notes/new/?next={quote(target)}',
                           {'title': 'Redirect test', 'body': 'Where do we go?'})
    print(f'{target:28} -> {response["Location"]}')

quote() encodes the target for the query string. The script creates a few private notes as a side effect; their numbers show up later.

Our site redirects to any address. An attacker sends a link that points to our real domain, with next leading to a copy of our login page on their own server; the user trusts the link and types the password into the copy. The target //evil.example/ has no scheme; the browser completes it with the current one, so a check that only looks for http misses it. HttpResponseRedirect itself refuses only schemes other than http, https, and ftp, such as javascript:, with DisallowedRedirect.

$ uv run python -m demos.redirects
/search/?q=plans             -> /search/?q=plans
https://evil.example/login/  -> https://evil.example/login/
//evil.example/              -> //evil.example/
http://localhost/search/     -> http://localhost/search/

Checking the redirect target

The function url_has_allowed_host_and_scheme() from django.utils.http returns true for relative URLs and for absolute URLs whose host is in the given set, and with require_https it also rejects plain HTTP. We use it in a small helper.

notes/views.py
from django.utils.http import url_has_allowed_host_and_scheme
...


def next_url(request, default):
    url = request.GET.get('next')
    if url and url_has_allowed_host_and_scheme(
            url, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
        return url
    return default


@login_required
def note_create(request):
    form = NoteForm(request.POST or None)
    if form.is_valid():
        form.instance.owner = request.user
        note = form.save()
        return redirect(next_url(request, note.get_absolute_url()))
    return render(request, 'notes/form.html', {'form': form})

next_url() returns the next parameter if it stays on our host, and the default otherwise. Django's own LoginView and LogoutView check their next parameter the same way, and the setting ALLOWED_HOSTS makes sure that the host from get_host() is one of ours.

The relative URL and the absolute URL with our own host pass; the two foreign targets are replaced with the URL of the new note.

$ uv run python -m demos.redirects
/search/?q=plans             -> /search/?q=plans
https://evil.example/login/  -> /notes/13/
//evil.example/              -> /notes/14/
http://localhost/search/     -> http://localhost/search/

CSRF and the Origin header

The basics of cross-site request forgery and the {% csrf_token %} tag are explained in Django forms. The token is not the only check of CsrfViewMiddleware: when a browser sends the Origin header, which modern browsers do for every POST request, the middleware compares it with the host of the request. The demo script sends a valid token with different headers.

demos/origins.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()


from django.contrib.auth.models import User
from django.test import Client

client = Client(SERVER_NAME='localhost', enforce_csrf_checks=True)
client.force_login(User.objects.get(username='bob'))
client.get('/notes/new/')
data = {'title': 'Origin test', 'body': 'Who sent this?',
        'csrfmiddlewaretoken': client.cookies['csrftoken'].value}

for origin in [None, 'http://localhost', 'https://evil.example', 'null']:
    headers = {'Origin': origin} if origin else {}
    response = client.post('/notes/new/', data, headers=headers)
    print(f'Origin {origin}: {response.status_code}')

response = client.post('/notes/new/', data, secure=True)
print('HTTPS without Referer:', response.status_code)
response = client.post('/notes/new/', data, secure=True,
                       headers={'Referer': 'https://localhost/notes/new/'})
print('HTTPS with Referer:', response.status_code)

The script loads the form to get the CSRF cookie and puts its value into the form data. Then it posts the form without an Origin header, with our own origin, with a foreign one, and with null, which browsers send from sandboxed frames and some redirects. The last two requests use HTTPS (secure=True).

Even with a valid token, a request from a foreign origin is rejected with 403, and the django.security.csrf logger says why. A missing header is accepted, because older clients do not send it. Over HTTPS, a request without Origin must have a Referer header from our host. A front end on another domain that posts to our site must be listed in the setting CSRF_TRUSTED_ORIGINS, for example ['https://app.example.com']. The CSRF and session cookies also have SameSite=Lax by default, so browsers do not send them with POST requests started by other sites; see Django sessions and cookies.

$ uv run python -m demos.origins
Origin None: 302
Origin http://localhost: 302
Forbidden (Origin checking failed - https://evil.example does not match any trusted origins.): /notes/new/
Origin https://evil.example: 403
Forbidden (Origin checking failed - null does not match any trusted origins.): /notes/new/
Origin null: 403
Forbidden (Referer checking failed - no Referer.): /notes/new/
HTTPS without Referer: 403
HTTPS with Referer: 302

Clickjacking

In a clickjacking attack, a foreign page loads our page into an invisible frame and places it over its own buttons; the user thinks they click the foreign page, but they click our page, where they are logged in. XFrameOptionsMiddleware adds the header X-Frame-Options: DENY to every response, which tells browsers not to show the page in a frame at all. A page meant to be embedded by other sites, such as a widget with a public note, needs an exception.

notes/views.py
from django.views.decorators.clickjacking import xframe_options_exempt
...


@xframe_options_exempt
def note_embed(request, pk):
    note = get_object_or_404(Note, pk=pk, public=True)
    return render(request, 'notes/detail.html', {'note': note})

xframe_options_exempt removes the header for this view; the decorator xframe_options_sameorigin allows frames on our own site, and the setting X_FRAME_OPTIONS = 'SAMEORIGIN' does that for the whole project. The view shows only public notes. The final URLconf has the new route.

notes/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('search/', views.search, name='search'),
    path('notes/<int:pk>/', views.note_detail, name='note-detail'),
    path('notes/new/', views.note_create, name='note-create'),
    path('notes/<int:pk>/embed/', views.note_embed, name='note-embed'),
]

The embed page has no header, the home page has DENY. The 404 response for a private note has the header again: it is created by Django's error handler, not by the decorated view. The modern replacement of the header is the CSP directive frame-ancestors, which can list the sites that may embed a page; see Django Content Security Policy.

$ curl -sI localhost:8000/notes/3/embed/ | grep -iE '^(HTTP|x-frame)'
HTTP/1.1 200 OK
$ curl -sI localhost:8000/ | grep -iE '^(HTTP|x-frame)'
HTTP/1.1 200 OK
X-Frame-Options: DENY
$ curl -sI localhost:8000/notes/1/embed/ | grep -iE '^(HTTP|x-frame)'
HTTP/1.1 404 Not Found
X-Frame-Options: DENY

The complete views module

The views were shown in parts; here is the whole module with all the fixes.

notes/views.py
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.html import format_html
from django.utils.http import url_has_allowed_host_and_scheme
from django.views.decorators.clickjacking import xframe_options_exempt

from .forms import NoteForm
from .models import Note


def home(request):
    notes = Note.objects.filter(public=True).select_related('owner')
    return render(request, 'notes/list.html', {'notes': notes})


SORTS = {'title': 'title', 'new': '-created', 'old': 'created'}


def search(request):
    q = request.GET.get('q', '')
    order = SORTS.get(request.GET.get('sort'), 'title')
    notes = (Note.objects.filter(public=True, title__icontains=q)
             .select_related('owner').order_by(order))
    message = format_html('Results for <b>{}</b>.', q)
    return render(request, 'notes/list.html', {'notes': notes, 'q': q, 'message': message})


def visible_notes(user):
    return Note.objects.filter(Q(owner=user) | Q(public=True))


@login_required
def note_detail(request, pk):
    note = get_object_or_404(visible_notes(request.user), pk=pk)
    return render(request, 'notes/detail.html', {'note': note})


def next_url(request, default):
    url = request.GET.get('next')
    if url and url_has_allowed_host_and_scheme(
            url, allowed_hosts={request.get_host()}, require_https=request.is_secure()):
        return url
    return default


@login_required
def note_create(request):
    form = NoteForm(request.POST or None)
    if form.is_valid():
        form.instance.owner = request.user
        note = form.save()
        return redirect(next_url(request, note.get_absolute_url()))
    return render(request, 'notes/form.html', {'form': form})


@xframe_options_exempt
def note_embed(request, pk):
    note = get_object_or_404(Note, pk=pk, public=True)
    return render(request, 'notes/detail.html', {'note': note})

Every view that reads data either shows only public notes or limits the query to the notes that the user may see, the search uses the ORM with an allow-list for the order, and the form view sets the owner itself and checks the redirect target. The system check finds no problems, which also means that it cannot find the bugs of this article: they are in our code, not in the settings.

$ uv run python manage.py check
System check identified no issues (0 silenced).

Testing security

Each fix deserves a test, so that a later change does not open the hole again. The tests repeat the attacks of the article against the test database.

notes/tests.py
from django.contrib.auth.models import User
from django.test import TestCase

from .models import Note


class SecurityTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.alice = User.objects.create_user('alice')
        cls.bob = User.objects.create_user('bob')
        cls.secret = Note.objects.create(owner=cls.alice, title='Wi-Fi', body='hunter2')
        Note.objects.create(owner=cls.bob, title='Hi', public=True,
                            body='<script>alert(1)</script>')

    def test_body_is_escaped(self):
        response = self.client.get('/')
        self.assertContains(response, '&lt;script&gt;alert(1)&lt;/script&gt;')
        self.assertNotContains(response, '<script>')

    def test_search_is_not_injectable(self):
        response = self.client.get('/search/', {'q': "' OR 1=1 --"})
        self.assertNotContains(response, 'Wi-Fi')

    def test_unknown_sort_is_ignored(self):
        response = self.client.get('/search/', {'sort': 'owner__password'})
        self.assertEqual(response.status_code, 200)

    def test_private_note_is_hidden(self):
        self.client.force_login(self.bob)
        response = self.client.get(f'/notes/{self.secret.pk}/')
        self.assertEqual(response.status_code, 404)

    def test_owner_cannot_be_forged(self):
        self.client.force_login(self.bob)
        data = {'title': 'IOU', 'body': 'Signed, Alice', 'owner': self.alice.pk}
        self.client.post('/notes/new/', data)
        self.assertEqual(Note.objects.get(title='IOU').owner, self.bob)

    def test_foreign_next_is_ignored(self):
        self.client.force_login(self.bob)
        data = {'title': 'Trip', 'body': 'Day one'}
        response = self.client.post('/notes/new/?next=https://evil.example/', data)
        self.assertRedirects(response, Note.objects.get(title='Trip').get_absolute_url())

    def test_page_cannot_be_framed(self):
        response = self.client.get('/')
        self.assertEqual(response['X-Frame-Options'], 'DENY')

The users are created without passwords, which keeps the tests fast; force_login() does not need one. The tests check that the body is escaped, that the injection finds nothing, that an unknown sort order does not fail, that bob gets 404 for alice's note, that the forged owner is ignored, that a foreign next leads to the new note, and that the home page cannot be framed. The test client skips CSRF checks by default, so the POST requests need no token.

$ uv run python manage.py test -v 2
Found 7 test(s).
Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
System check identified no issues (0 silenced).
test_body_is_escaped (notes.tests.SecurityTests.test_body_is_escaped) ... ok
test_foreign_next_is_ignored (notes.tests.SecurityTests.test_foreign_next_is_ignored) ... ok
test_owner_cannot_be_forged (notes.tests.SecurityTests.test_owner_cannot_be_forged) ... ok
test_page_cannot_be_framed (notes.tests.SecurityTests.test_page_cannot_be_framed) ... ok
test_private_note_is_hidden (notes.tests.SecurityTests.test_private_note_is_hidden) ... ok
test_search_is_not_injectable (notes.tests.SecurityTests.test_search_is_not_injectable) ... ok
test_unknown_sort_is_ignored (notes.tests.SecurityTests.test_unknown_sort_is_ignored) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.026s

OK
Destroying test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...

Source

Django documentation: Security in Django

Django documentation: format_html

Django documentation: Cross Site Request Forgery protection

Django documentation: Clickjacking Protection

OWASP Top 10

In this article we have attacked a small Django application and fixed it: we kept auto-escaping on and built HTML in Python with format_html(), passed values to raw SQL as parameters, allowed only known sort orders, limited queries to the objects the user may see, listed the fields of a form explicitly, checked redirect targets with url_has_allowed_host_and_scheme(), looked at the Origin check of the CSRF middleware and at clickjacking protection, and tested the fixes. Related articles are Django settings and environment, Django authentication, Django permissions and groups, Django Content Security Policy, and Django deployment.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.