Authentication Backends
Authentication backends control how users authenticate. The default backend checks username/password against the database. You can create custom backends to authenticate via email, LDAP, OAuth, or any custom method.
15 min•By Priygop Team•Updated 2026
Backend Concepts
- ModelBackend — Default, authenticates with username + password
- Custom backends subclass BaseBackend
- authenticate(request, **credentials) — Verify credentials
- get_user(user_id) — Retrieve user by ID
- AUTHENTICATION_BACKENDS setting — list of backend classes
- Django tries each backend in order until one succeeds
- Common custom: login with email instead of username
Email Auth Backend
Email Auth Backend
# accounts/backends.py
# from django.contrib.auth.backends import ModelBackend
# from django.contrib.auth import get_user_model
# User = get_user_model()
# class EmailBackend(ModelBackend):
# """Allow login with email instead of username"""
# def authenticate(self, request, username=None, password=None, **kwargs):
# try:
# # Try email first
# user = User.objects.get(email=username)
# except User.DoesNotExist:
# try:
# # Fallback to username
# user = User.objects.get(username=username)
# except User.DoesNotExist:
# return None
#
# if user.check_password(password) and self.user_can_authenticate(user):
# return user
# return None
# settings.py
# AUTHENTICATION_BACKENDS = [
# 'accounts.backends.EmailBackend',
# ]
# Now users can login with email OR username
# authenticate(request, username='alice@example.com', password='pass')
# authenticate(request, username='alice', password='pass')Tip
Tip
Create custom authentication backends for social login, LDAP, or API-based auth. Register them in AUTHENTICATION_BACKENDS.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not handling failed authentication gracefully. Always check if authenticate() returns None and show a clear error.
Practice Task
Note
(1) Create a custom auth backend. (2) Support email-based login. (3) Register it in AUTHENTICATION_BACKENDS.
Quick Quiz
Key Takeaways
- Authentication backends control how users authenticate.
- ModelBackend — Default, authenticates with username + password
- Custom backends subclass BaseBackend
- authenticate(request, **credentials) — Verify credentials