Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 77 ยท Authentication and Security

Users and Authentication

Learn how Django authentication works: the User model, password hashing, authenticate(), login(), logout(), login_required and the built-in auth views.

Almost every real website needs to know who is using it. Django ships with an authentication system in django.contrib.auth that covers users, password storage, login and logout, sessions, permissions and ready-made views. You rarely need a separate library, and the pieces are the same ones the admin uses.

In this lesson you will create users, see how passwords are stored, call authenticate() and login(), protect views with login_required, and learn which built-in views and URLs Django provides. Permissions and groups come in a later lesson, and replacing the User model is covered in Custom User Models.

Authentication, step by step

Authentication answers "who are you?". Authorization answers "what may you do?". Django keeps them apart. The flow for a password login looks like this:

sequenceDiagram
    participant B as Browser
    participant V as Login view
    participant A as authenticate()
    participant S as Session
    B->>V: POST username and password
    V->>A: check credentials
    A-->>V: User or None
    V->>S: login(request, user)
    S-->>B: session cookie
    B->>V: next request with cookie
    V-->>B: request.user is the User

authenticate() checks credentials, login() stores the user id in the session, and the middleware turns the session cookie into request.user on every later request.

Two details matter. First, authenticate() never changes the session; it only returns a user or None. Second, login() is what remembers the user. Splitting them lets you run extra checks (a captcha, a "terms accepted" flag) between the two steps.

The User model

The built-in User model has the fields most sites need:

Field Meaning
username Unique login name (letters, digits and @ . + - _)
password A hash of the password, never the password itself
email, first_name, last_name Optional profile data
is_active Inactive users cannot log in. Use it instead of deleting accounts
is_staff May enter the admin site
is_superuser Has every permission without needing to be granted any
last_login, date_joined Timestamps maintained for you
groups, user_permissions Used for authorization

Never call User(...) and save() with a raw password. Use User.objects.create_user(...), which hashes the password, and create_superuser(...) for administrators. To change a password later, call set_password() and then save().

Passwords are hashed, not encrypted

Django stores a one-way hash built with a deliberately slow algorithm (PBKDF2 by default). A salt makes every hash unique, even for identical passwords. To check a password Django hashes the candidate the same way and compares the results. Nobody, including you, can read the original password from the database.

The slowness is intentional: it makes brute-force guessing expensive for an attacker. The default settings use a very high iteration count, which would be far too slow in a browser. On top of that, the Python build that runs in your browser has no PBKDF2 function at all. So the demo below does two things that are for demonstration only: it adds a small pure-Python PBKDF2 stand-in so you can see the real hash format (with just 1,000 iterations), and it lists a quick hasher first in PASSWORD_HASHERS so that this page stays fast. Never do either in production; a real server keeps Django's defaults.

Python Users, passwords and authenticate()

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.

Notice that authenticate() returns None for a wrong password, an unknown user and an inactive user alike. It does not tell the caller which one failed, which is exactly what you want in a login form: telling attackers "that username does not exist" helps them.

Login, logout and protecting views

On the request side, three tools do most of the work:

  • authenticate(request, username=..., password=...) returns a User or None.
  • login(request, user) attaches the user to the session. Django also rotates the session key to prevent session fixation.
  • logout(request) flushes the session. Since Django 5.0 the built-in LogoutView accepts only POST, so a link from another site cannot log your users out.

Every request passing through AuthenticationMiddleware has request.user. It is a real User for logged-in visitors and an AnonymousUser otherwise, so request.user.is_authenticated is always safe to read. Templates get the same object as user when the auth context processor is enabled.

To require a login, decorate a function view with @login_required. Anonymous visitors are redirected to settings.LOGIN_URL with a ?next= parameter so they return to the page afterwards. Class-based views use LoginRequiredMixin (more in Permissions, Groups and Authorization). Since Django 5.1 you can also add LoginRequiredMiddleware to require a login on every view by default, then mark public views with @login_not_required.

Python Login, logout and login_required with the test client

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 sequence matches the diagram: the redirect to /login/?next=/profile/, the session set by a good login, the 405 for a GET logout and the POST that clears it. Because the test client keeps cookies between calls, it behaves like one browser.

Built-in views and URLs

You do not have to write login, logout and password-reset pages. One line wires them all:

Python
# project/urls.py
from django.urls import include, path

urlpatterns = [
    path("accounts/", include("django.contrib.auth.urls")),
]

That gives you these named URLs, each with a class-based view you can also use on its own:

URL name View Purpose
login LoginView Log in with AuthenticationForm
logout LogoutView Log out (POST only)
password_change, password_change_done PasswordChangeView Change password while logged in
password_reset, password_reset_done PasswordResetView Ask for a reset email
password_reset_confirm, password_reset_complete PasswordResetConfirmView Set a new password from the emailed link

The views render templates under registration/ (such as registration/login.html), which you supply in your own templates folder; the admin has its own copies, which is why the admin's login page works with no setup. Three settings control the redirects: LOGIN_URL (where anonymous users are sent), LOGIN_REDIRECT_URL (where to go after login if there is no next) and LOGOUT_REDIRECT_URL.

Registration (sign-up) is not part of django.contrib.auth.urls. You build it yourself with UserCreationForm (or a ModelForm) and a CreateView, then call login() for the new user if you want them signed in immediately.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does authenticate() do when the password is correct?

    authenticate() only verifies credentials and returns a User or None. You must call login(request, user) to remember the user in the session.
  2. 2. Why should you create users with create_user() instead of User(...).save() with a password argument?

    The password field holds a hash. create_user() (or set_password()) produces it. Assigning a raw string to password would store the plain text, and login would fail.
  3. 3. What happens when an anonymous visitor requests a view decorated with @login_required?

    login_required redirects to settings.LOGIN_URL and adds the original path as the next parameter, so the login view can send the user back afterwards.
  4. 4. Why does the built-in LogoutView only accept POST requests?

    Logging out changes state, and state-changing actions should not be triggered by GET requests. A POST (with a CSRF token) cannot be fired by a cross-site link or image.

Summary

  • django.contrib.auth provides users, password hashing, sessions integration, permissions and ready-made views.
  • Create users with create_user() / create_superuser(); passwords are salted, slow hashes and cannot be read back.
  • authenticate() returns a user or None; login() stores the user in the session; logout() flushes it.
  • request.user is a User or AnonymousUser; check is_authenticated.
  • @login_required, LoginRequiredMixin and LoginRequiredMiddleware protect views; LOGIN_URL and next handle redirects.
  • include("django.contrib.auth.urls") adds login, logout and password views; you provide the registration/ templates and your own sign-up view.

Next up: Custom User Models.