python 43 lines · 2 tabs

Django custom authentication backend

Priya Sharma Jan 2026
2 tabs
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model

User = get_user_model()


class EmailBackend(ModelBackend):
    """Authenticate using email instead of username."""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # username parameter contains email
        try:
            user = User.objects.get(email=username)
        except User.DoesNotExist:
            return None

        if user.check_password(password) and self.user_can_authenticate(user):
            return user

        return None


class TokenBackend(ModelBackend):
    """Authenticate using API token."""

    def authenticate(self, request, token=None, **kwargs):
        if not token:
            return None

        try:
            from api.models import ApiToken
            api_token = ApiToken.objects.select_related('user').get(
                key=token,
                is_active=True
            )
            return api_token.user
        except ApiToken.DoesNotExist:
            return None
2 files · python Explain with highlit

Custom auth backends enable alternative authentication methods. I subclass ModelBackend and override authenticate(). Common use cases include email login, LDAP, OAuth, or custom token auth. The backend returns a user object or None. I add it to AUTHENTICATION_BACKENDS in settings. Multiple backends can coexist—Django tries each in order. For permissions, I override get_user_permissions() and get_group_permissions(). This extends authentication beyond username/password without replacing Django's auth system.


Related snips

ruby
payload = {
  sub: user.id,
  iss: 'https://auth.example.com',
  aud: 'codesnips-api',
  exp: 15.minutes.from_now.to_i,
  iat: Time.now.to_i,

JWT issuance and verification without common footguns

jwt authentication api
by Kai Nakamura 2 tabs
python
import os
import stat

for root, _dirs, files in os.walk('/etc'):
    for name in files:
        path = os.path.join(root, name)

Python security audit script for exposed risky filesystem state

python auditing host-security
by Kai Nakamura 1 tab
python
class Product(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    cost = models.DecimalField(max_digits=10, decimal_places=2)
    margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)

Django model signals vs overriding save

django python models
by Priya Sharma 2 tabs
python
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [

Django URL namespacing and reverse lookups

django python urls
by Priya Sharma 3 tabs
typescript
import { randomBytes, createHash } from "crypto";
import jwt from "jsonwebtoken";
import { RefreshTokenStore } from "./store";

const ACCESS_SECRET = process.env.ACCESS_SECRET!;
const ACCESS_TTL = "15m";

JWT access + refresh token rotation (conceptual)

security node jwt
by codesnips 3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment


class PostType(DjangoObjectType):

Django GraphQL with Graphene

django python graphql
by Priya Sharma 2 tabs

Share this code

Here's the card — post it anywhere.

Django custom authentication backend — share card
Link copied