The Django Authentication System is a comprehensive, built-in framework that handles user accounts, groups, permissions, cookie-based sessions, and secure password hashing.
Building a secure login system is incredibly complex and risky. Django provides a robust, heavily audited system out of the box. It manages who is logged in (authentication) and what they are allowed to do (authorization).
- Enabled by default via
django.contrib.authanddjango.contrib.sessions. - Provides a base
Usermodel containing username, email, password (hashed), and permission flags. - Middleware checks the session cookie on incoming requests and attaches the
Userobject torequest.user. - Views can use decorators like
@login_requiredto restrict access. - Passwords are never stored in plain text; they are hashed using algorithms like PBKDF2.
graph LR A[Client sends Credentials] --> B(Auth Backend checks Hash) B -->|Valid| C(Session Created & Cookie Sent) C --> D[Subsequent Requests use Cookie] D --> E(Middleware sets request.user)
Authentication is the security guard checking your ID at the front door to verify you are who you say you are. Authorization (Permissions) is the access badge that determines which specific rooms in the building you are allowed to enter.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def secret_page(request):
return render(request, 'secret.html')- Pluggable: You can define a Custom User Model (highly recommended at the start of a project).
- Secure: Handles session hijacking prevention, password hashing, and CSRF protection.
- Includes Groups and Permissions for granular access control.
- Built from: Django Web Framework — built-in security layer.
- Related: Django Admin Panel — relies heavily on the auth system.
- Related: Django Model — User is a model.
- Related: Django Request-Response Lifecycle — sessions are handled in middleware.
- It is extremely difficult to switch to a Custom User Model mid-project. It is best practice to configure a Custom User Model in
settings.pybefore running the very first migration.