← Back to Django, page 3

django-0049 · Hard senior

How do you write a custom authentication backend in Django, for example to log in with email, and how do object-level permissions fit in?

A backend is a class with authenticate(request, **credentials) returning a user or None, and get_user(user_id). Add it to AUTHENTICATION_BACKENDS; Django tries backends in order. Backends can also implement has_perm(user_obj, perm, obj=None) for object-level permissions, which Django's built-in ModelBackend does not provide for specific objects. Packages like django-guardian or django-rules are common for that.

Full answer

authenticate() loops over settings.AUTHENTICATION_BACKENDS. The first backend that returns a user wins. If a backend raises PermissionDenied, the loop stops and authentication fails.

An email backend:

python
class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(email__iexact=username)
        except User.DoesNotExist:
            User().set_password(password)   # spend similar time to resist timing attacks
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

Details:

  • Subclassing ModelBackend keeps get_user(), group and model permission checks, and user_can_authenticate() (rejects inactive users).
  • Email must be unique for this to be safe. Enforce it with a database constraint, ideally case-insensitive (a UniqueConstraint on Lower("email")).
  • Running the password hasher even for unknown emails keeps response time similar, so attackers cannot discover registered emails by timing.
  • Django stores the backend path in the session at login, and get_user() of that backend loads the user on later requests.
  • Rate limit login attempts separately (proxy rules, django-axes).

Object-level permissions:

  • user.has_perm("school.change_note") checks model-level permission: may this user edit any note?
  • user.has_perm("school.change_note", note) passes an object. ModelBackend returns False for any object-level check. A custom backend can implement has_perm(user_obj, perm, obj=None) to say yes for the note's owner.
  • Django combines backends with OR: if any backend grants the permission, has_perm is True.
  • django-guardian stores per-object grants in tables; django-rules uses predicate functions without tables.

In DRF, object permissions are usually expressed in permission classes, but a backend keeps the rule in one place that the admin and templates can use too.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth import authenticate, get_user_model
from django.contrib.auth.backends import BaseBackend, ModelBackend
from django.core.management import call_command
from django.db import connection, models

settings.PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]  # fast, demo only
settings.AUTHENTICATION_BACKENDS = ["__main__.EmailBackend", "__main__.OwnerBackend"]
call_command("migrate", verbosity=0)
User = get_user_model()


class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(email__iexact=username)
        except User.DoesNotExist:
            User().set_password(password)   # similar timing for unknown emails
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user
        return None


class Note(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.CharField(max_length=100)
    class Meta:
        app_label = "school"


class OwnerBackend(BaseBackend):
    def has_perm(self, user_obj, perm, obj=None):
        return perm == "school.change_note" and isinstance(obj, Note) and obj.owner_id == user_obj.id


with connection.schema_editor() as editor:
    editor.create_model(Note)

rina = User.objects.create_user("rina", email="Rina@Example.edu", password="Notebook-42")
sam = User.objects.create_user("sam", email="sam@example.edu", password="x")
User.objects.create_user("old", email="old@example.edu", password="x", is_active=False)

print(authenticate(username="rina@example.edu", password="Notebook-42"))
print(authenticate(username="rina@example.edu", password="wrong"))
print(authenticate(username="old@example.edu", password="x"))

note = Note.objects.create(owner=rina, text="Chemistry practical list")
print(rina.has_perm("school.change_note"), rina.has_perm("school.change_note", note),
      sam.has_perm("school.change_note", note))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. MD5 hashing is used only to keep the demo fast. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): rina None None False True False

Key points

  • authenticate() returns a user or None; backends are tried in order
  • Subclass ModelBackend to keep get_user and permission checks
  • Enforce unique, case-insensitive emails
  • has_perm(user, perm, obj) enables object-level rules
  • Backends combine with OR for permissions

Common mistakes

  • Allowing duplicate emails and logging in the wrong account
  • Returning early for unknown emails and leaking which emails exist through timing
  • Forgetting to check is_active
  • Expecting ModelBackend to answer object-level permission checks

Follow-ups

  • How would you add login with a one-time code sent by SMS?
  • How do multiple backends combine for has_perm?
  • How would you share the same object rules between the admin and a DRF API?

Tips

  • Show both authenticate and has_perm on a backend
  • Mention the timing attack defence
  • Know that Django combines permission backends with OR