Thuta Learning
Python
IntermediateProgrammingBeginner

Django Authentication

PythonLesson 4140 min

What you'll walk away with

  • Explain the difference between authentication and authorization with an example
  • Create a user with create_user() and verify the password is stored as a hash, not plain text
  • Explain how authenticate(), login() and logout() relate to the session
  • Use @login_required and @permission_required and tell a 302 redirect from a 403
  • Check ownership of an individual object on the server, inside the view

Explain it simply

Authentication in plain language

Every system with a login has to answer two questions. The first is 'who are you?', called authentication: checking a username and password. The second is 'are you allowed to do this?', called authorization. Django ships built-in tools for both.

Take an office building. At reception you show your ID and receive a badge: that is authentication. Having a badge does not open the server room; each door checks what the badge allows, and that is authorization. In Django the badge is the session cookie and each door is a view.

Problem → Why → Solution

The problem: assuming a hidden button is security

In a note app, the template uses {% if note.owner == user %} to show the Delete button only to the owner. But the delete view itself checks nothing. Any logged-in user can type /notes/7/delete/ into the address bar, or loop over ids, and delete someone else's note. This is called IDOR (insecure direct object reference), and it is one of the most common security bugs in web apps.

views.py
@login_required
def delete_note(request, note_id):
    note = Note.objects.get(pk=note_id)
    note.delete()  # never checks note.owner == request.user
    return redirect("note-list")

Why the check must happen on the server

An if in a template only controls what is displayed; it stops no one from sending a request. @login_required only checks 'is someone logged in?', not 'is this note theirs?'. Authorization is only safe when the view checks it on every request and raises PermissionDenied (403) when the answer is no.

Core concept: password hashes, sessions and permissions

django.contrib.auth provides the User model. User.objects.create_user("mya", email, "password") never stores the password directly: it turns it into a salted hash stored as algorithm$iterations$salt$hash, using PBKDF2 by default. A hash cannot be reversed, so even a leaked database does not reveal the real passwords. user.check_password("...") hashes the typed password again and compares.

authenticate(request, username=..., password=...) returns the User when the credentials are right and None when they are wrong; it does not raise. login(request, user) stores the user's id in the session and sends a session cookie to the browser. On later requests, AuthenticationMiddleware rebuilds request.user from that cookie. For a visitor who has not logged in, request.user is an AnonymousUser whose is_authenticated is False. logout(request) clears the session.

ToolChecks / on failure
@login_requiredlogged in? / 302 redirect to LOGIN_URL?next=...
@permission_required(..., raise_exception=True)has the permission? / 403 Forbidden
ownership check in the viewis this object theirs? / PermissionDenied (403)

Permissions are written as "app_label.codename", for example "auth.view_user". For every model, migrate creates four permissions automatically, add, change, delete and view, which you can grant to users or groups. user.has_perm() always returns True for an active superuser. These permissions apply to the whole model; an object-level check such as 'this particular note' is something you write yourself in the view.

Password hashing is slow on purpose: PBKDF2 repeats its calculation for many iterations, which is unnoticeable for one login but makes guessing millions of passwords very expensive for an attacker. The AUTH_PASSWORD_VALIDATORS setting also rejects passwords that are too short, entirely numeric or too common. In templates, {{ user.username }} and {% if user.is_authenticated %} let the page change depending on the login state.

Badge and doors
  1. authenticate(): who are you?
  2. login(): issue the session badge
  3. Middleware: cookie -> request.user
  4. View: login, permission, owner

Having a badge (authenticated) is not the same as being allowed through a door (authorized); every door needs its own check.

General pattern

python
user = authenticate(request, username=name, password=secret)  # User or None
if user is not None:
    login(request, user)            # stores the id in the session

@login_required                     # anonymous -> 302 to LOGIN_URL
def some_view(request, pk):
    obj = get_object_or_404(Model, pk=pk)
    if obj.owner != request.user:   # object-level authorization
        raise PermissionDenied      # -> 403
    return render(request, "app/page.html", {"obj": obj})

When logging in, call authenticate() and then login(). In every protected view, check login with a decorator, then check ownership after you have fetched the object.

Worked example: hashing, login, redirect and 403

Auth needs database tables, so this demo uses settings.configure() with an in-memory SQLite database and creates the tables with call_command("migrate"). That is only so it runs as one file; in a real project these settings already sit in settings.py and you run python manage.py migrate in a terminal.

The script creates a user, tries a wrong and a right password, then uses the test Client to call two protected pages before and after logging in. Password hashing is slow by design, so the run can take a second or so.

auth_demo.py
import django
from django.conf import settings

# Single-file demo only: a real project's settings.py already has all of this.
settings.configure(
    SECRET_KEY="demo-only-not-a-real-secret",
    ALLOWED_HOSTS=["testserver"],
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes",
                    "django.contrib.sessions"],
    MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
                "django.contrib.auth.middleware.AuthenticationMiddleware"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.core.management import call_command
from django.http import HttpResponse
from django.test import Client
from django.urls import path

call_command("migrate", verbosity=0)  # creates the auth and session tables


@login_required
def dashboard(request):
    return HttpResponse(f"Hello, {request.user.username}")


@permission_required("auth.view_user", raise_exception=True)
def user_report(request):
    return HttpResponse("secret report")


urlpatterns = [path("dashboard/", dashboard), path("report/", user_report)]

user = User.objects.create_user("mya", "mya@example.com", "correct-horse-42")
print("stored hash:", user.password.split("$")[0])
print("wrong password:", authenticate(username="mya", password="guess"))
print("right password:", authenticate(username="mya", password="correct-horse-42"))

client = Client()
response = client.get("/dashboard/")
print("anonymous:", response.status_code, response["Location"])

client.login(username="mya", password="correct-horse-42")
print("logged in:", client.get("/dashboard/").content.decode())
print("report without permission:", client.get("/report/").status_code)

Code breakdown

  1. Auth needs these apps INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes",

    auth provides the User and Permission models, and contenttypes records which model each permission belongs to. sessions plus the two middleware classes carry the login state from one request to the next.

  2. Hash, not plain textprint("stored hash:", user.password.split("$")[0])

    create_user() stores a hash shaped like pbkdf2_sha256$... in the password field. This line prints only the algorithm name, because the salt and hash change on every run.

  3. Wrong password returns Noneprint("wrong password:", authenticate(username="mya", password="guess"))

    authenticate() returns None rather than raising, so a login view checks if user is not None:. With the right password it returns the User, which prints as its username.

  4. Anonymous visitorprint("anonymous:", response.status_code, response["Location"])

    @login_required sends an anonymous user a 302 to /accounts/login/ (the default LOGIN_URL), and ?next=/dashboard/ remembers where to return after logging in.

  5. Logged in, still not allowedprint("report without permission:", client.get("/report/").status_code)

    mya is logged in but lacks the auth.view_user permission. Because of raise_exception=True the answer is a 403 rather than another redirect to the login page: authenticated, yet not authorized.

You should see
stored hash: pbkdf2_sha256
wrong password: None
right password: mya
anonymous: 302 /accounts/login/?next=/dashboard/
logged in: Hello, mya
report without permission: 403

Register, login and logout in a real project

You do not have to write login and logout yourself. Adding include("django.contrib.auth.urls") to urls.py gives you login/, logout/, password_change/, password_reset/ and more, and you only write a registration/login.html template. Registration you write yourself with UserCreationForm, which checks that the two passwords match, runs the password validators and hashes the password when it saves.

accounts/views.py
from django.contrib.auth import login
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect, render


def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()          # hashes the password
            login(request, user)        # log the new user straight in
            return redirect("dashboard")
    else:
        form = UserCreationForm()
    return render(request, "registration/register.html", {"form": form})


# urls.py
# path("accounts/", include("django.contrib.auth.urls")),
# path("accounts/register/", register, name="register"),
templates/base.html (logout part)
{% if user.is_authenticated %}
  <form method="post" action="{% url 'logout' %}">
    {% csrf_token %}
    <button type="submit">Log out {{ user.username }}</button>
  </form>
{% else %}
  <a href="{% url 'login' %}">Log in</a>
{% endif %}

Since Django 5.0 the built-in LogoutView accepts only POST, so logging out is a form with a CSRF token rather than a plain link. That way another site cannot log your users out with an image tag. In class-based views, LoginRequiredMixin and PermissionRequiredMixin take the place of the decorators.

In real projects

Auth in real projects

Every app with accounts has roles: student, author and admin on a learning platform; customer, staff and manager in a shop. The usual pattern is one Group per role, permissions granted to the group, and users added to groups, so changing what a role may do never means editing users one by one.

  • Permission matrix tests: call each URL as each role (anonymous, student, author, admin) and assert the expected 302, 403 or 200 in a table-driven test.
  • Custom user model: define a custom User that subclasses AbstractUser at the start of a new project; switching halfway through causes painful migrations.
  • Production settings: set SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to True so cookies travel only over HTTPS, and rate-limit the login view against password guessing.

Common mistakes

Common mistakes with authentication

Creating users with User.objects.create(password=...)

create() puts the password string into the field without hashing it. The database now holds a plain-text password, and check_password() always returns False because the value is not in hash format, so the user cannot log in either. Always use create_user() or user.set_password().

Treating @login_required as authorization

@login_required only checks for 'some logged-in user'. Every view that edits, deletes or shows an object also needs an owner or permission check, or should query only within the user's own data, as in Note.objects.filter(owner=request.user).

Revealing exactly why a login failed

Saying 'this username does not exist' versus 'wrong password' lets an attacker list which usernames exist. Show one message, such as 'username or password is incorrect', which is exactly what the built-in AuthenticationForm does.

Mini challenge

Mini challenge: only the owner may edit a note

Write a view that edits a note. Anonymous visitors are redirected to the login page, users who do not own the note get a 403, and the owner or a superuser gets a 200. Send a request as four kinds of user and print the status codes.

  • Protect the edit_note view with @login_required
  • Raise Http404 for a missing note and PermissionDenied for a non-owner who is not a superuser
  • Create test users with create_user() and no password, and log in with client.force_login()
  • Print the status code for anonymous, another user, the owner and a superuser
owner_only.py
import django
from django.conf import settings

settings.configure(
    SECRET_KEY="demo-only-not-a-real-secret",
    ALLOWED_HOSTS=["testserver"],
    ROOT_URLCONF=__name__,
    # TODO: INSTALLED_APPS (auth, contenttypes, sessions), MIDDLEWARE
    # (session + authentication) and an in-memory sqlite3 DATABASES entry
)
django.setup()

from django.core.management import call_command
from django.urls import path

call_command("migrate", verbosity=0)

NOTES = {1: {"owner": "aung", "text": "Buy milk"}}


def edit_note(request, note_id):
    # TODO: require login, 404 for unknown notes, 403 unless owner or superuser
    ...


urlpatterns = [path("notes/<int:note_id>/edit/", edit_note)]

# TODO: create users aung, hla and a superuser, then request the page as
# anonymous / hla / aung / superuser with a fresh Client each time

Expected: Four lines: anonymous -> 302, other user -> 403, owner -> 200, superuser -> 200.

Show hint

force_login() creates the session without checking a password, which keeps tests fast. create_superuser("boss", "boss@example.com", None) makes a superuser with no usable password. A Client keeps its cookies, so use a fresh Client per user.

Show solution
owner_only.py
import django
from django.conf import settings

settings.configure(
    SECRET_KEY="demo-only-not-a-real-secret",
    ALLOWED_HOSTS=["testserver"],
    ROOT_URLCONF=__name__,
    INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes",
                    "django.contrib.sessions"],
    MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware",
                "django.contrib.auth.middleware.AuthenticationMiddleware"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.core.management import call_command
from django.http import Http404, HttpResponse
from django.test import Client
from django.urls import path

call_command("migrate", verbosity=0)

NOTES = {1: {"owner": "aung", "text": "Buy milk"}}


@login_required
def edit_note(request, note_id):
    note = NOTES.get(note_id)
    if note is None:
        raise Http404("No such note")
    if note["owner"] != request.user.username and not request.user.is_superuser:
        raise PermissionDenied
    return HttpResponse(f"Editing: {note['text']}")


urlpatterns = [path("notes/<int:note_id>/edit/", edit_note)]

aung = User.objects.create_user("aung")  # no password: unusable, fine for tests
hla = User.objects.create_user("hla")
admin = User.objects.create_superuser("boss", "boss@example.com", None)

checks = [("anonymous", None), ("other user", hla), ("owner", aung), ("superuser", admin)]
for label, who in checks:
    client = Client()
    if who is not None:
        client.force_login(who)
    response = client.get("/notes/1/edit/")
    print(f"{label:<10} -> {response.status_code}")

Quick quiz 1 / 3

What does authenticate(username="mya", password="wrong") return?

Quick quiz 2 / 3

With default settings, what does an anonymous visitor get from /dashboard/, which uses @login_required?

Quick quiz 3 / 3

The template shows the Delete button only to the owner, and the delete view has only @login_required. What is still missing?

What to remember

  • Authentication is 'who are you', authorization is 'what may you do', and both are checked on the server.
  • create_user() and set_password() store a salted hash; never use create(password=...).
  • authenticate() returns a User or None, and login() ties the session cookie to request.user.
  • @login_required redirects anonymous visitors, missing permissions give a 403, and object ownership is checked in the view itself.

Django — Getting Started — Django Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Django Authentication | Thuta Learning