🔐 Supercharge Your Django API Authentication with drf-authentify

Authentication is a fundamental part of any API, but Django REST Framework’s built-in token authentication is limited. It only allows one token per user, lacks context-awareness, and has no built-in revocation tools.

That’s why I built drf_authentify: a simple, powerful, and flexible token authentication system for Django REST Framework (DRF) that solves those problems without adding unnecessary complexity.

In this article, I’ll walk you through what it is, why it’s useful, and how you can start using it in your Django project today.

✨ What is drf_authentify?

drf_authentify is a modern authentication utility for Django REST Framework that:

  • 🔑 Supports multiple tokens per user

  • 🔐 Adds access restrictions (header vs. cookie)

  • ⚙️ Provides token revocation utilities

  • 📦 Stores custom context data with tokens

  • 🔍 Makes token metadata easily accessible via request.auth

It's designed to feel familiar if you’ve used DRF, but with better defaults and extensibility.

📦 Installation

Install the library via pip:

pip install drf-authentify

Add it to your Django settings:

# settings.py

INSTALLED_APPS = [
    # your other apps...
    'drf_authentify',
]

Run the migrations:

python3 manage.py migrate

This creates the AuthToken model, visible and editable via the Django admin.

⚙️ Configuration

You can optionally configure global behaviour in settings.py:

DRF_AUTHENTIFY = {
    "COOKIE_KEY": "token",
    "ALLOWED_HEADER_PREFIXES": ["bearer", "token"],
    "TOKEN_EXPIRATION": 3000,
    "ENABLE_AUTH_RESTRICTION": False,
    "STRICT_CONTEXT_PARAMS_ACCESS": False,
}

What These Mean

SettingDescription
COOKIE_KEYName of the cookie used for auth
ALLOWED_HEADER_PREFIXESAcceptable prefixes in Authorization header
TOKEN_EXPIRATIONDefault token lifetime (in seconds)
ENABLE_AUTH_RESTRICTIONDisallow using cookie-token in headers (and vice versa)
STRICT_CONTEXT_PARAMS_ACCESSEnforce strict access to context keys

🧪 Token Generation

To create tokens, use the TokenService utility class:

from drf_authentify.services import TokenService

# Header-based token
token = TokenService.generate_header_token(user, context={"role": "admin"}, expires=3600)

# Cookie-based token
token = TokenService.generate_cookie_token(user, context={"device": "mobile"})

You can optionally specify expiration per token or attach any context dictionary for storing metadata like role, platform, IP address, etc.


🧹 Revoking Tokens

You can easily revoke tokens using built-in methods:

from drf_authentify.services import TokenService

# Revoke current token from a request
TokenService.revoke_token_from_request(request)

# Revoke all tokens for the user in a request
TokenService.revoke_all_tokens_for_user_from_request(request)

# Revoke all tokens for a user directly
TokenService.revoke_all_user_tokens(user)

# Revoke all expired tokens globally
TokenService.revoke_expired_tokens()

No more manually deleting tokens from the database!


🔐 Setting Up Authentication

Add drf_authentify's authentication classes to your DRF config:

# settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'drf_authentify.auth.CookieAuthentication',
        'drf_authentify.auth.AuthorizationHeaderAuthentication',
    ]
}

With this, drf_authentify, will handle authorization just fine.


🧠 Accessing Token Context

One of the best features is how easy it is to access the metadata associated with a token.

def my_view(request):
    user = request.user            # The authenticated user
    token = request.auth           # The AuthToken instance
    role = token.context.get("role")
    platform = token.context_obj.device  # dot-access

The context_obj lets you access context keys as attributes (context_obj.device), while context gives you the original dictionary.


📊 Admin Integration

Inside the Django admin panel, you’ll see a new AuthToken model. You can:

  • View active and expired tokens

  • Revoke or delete tokens manually

  • Inspect token context and creation method (header or cookie)

This makes it easy to manage tokens without needing to touch the DB directly.

📌 Final Thoughts

drf_authentify aims to strike the right balance between flexibility and simplicity. Whether you’re building a monolith, SPA, or microservices with Django APIs, it helps you:

  • Authenticate users securely

  • Manage tokens across devices or platforms

  • Store custom metadata for access control

Have questions or want to contribute? Feel free to open an issue or PR on GitHub.

1
Subscribe to my newsletter

Read articles from Gabriel Idenyi A directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gabriel Idenyi A
Gabriel Idenyi A

Full Stack Developer and graduate in Computer Engineering. Skilled in solving problems.