Django and DRF integration for Clerk authentication with request token verification, Clerk-to-Django user synchronization, cache-backed auth reuse, and Django signals for auth observability.
Project description
Django Clerk SDK
django-clerk-sdk is a Django and Django REST Framework integration for Clerk authentication.
It validates Clerk session tokens on incoming requests, syncs Clerk user data into your Django user model, caches successful authentications, and emits Django signals for observability.
What This Package Provides
ClerkMiddlewarefor request-level authentication in Django.ClerkAuthenticationfor DRF endpoints.ClerkClient/clerk_clientfor direct programmatic use.- Automatic user sync from Clerk to Django user records.
- Token-result caching through Django's cache backend.
- Signals for auth success, auth failure, and cache misses.
Installation
pip install django-clerk-sdk
Quick Setup
1. Add apps
INSTALLED_APPS = [
# ...
"django_clerk_sdk",
"django_clerk_sdk.users", # Optional if you want the included ClerkUser model
]
If you use the packaged user model:
AUTH_USER_MODEL = "users.ClerkUser"
2. Add middleware
Place Clerk middleware after Django auth middleware so session auth still works when no Clerk credentials are present.
MIDDLEWARE = [
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_clerk_sdk.core.auth.clerk.middleware.ClerkMiddleware",
# ...
]
3. Configure DRF authentication
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"django_clerk_sdk.core.auth.clerk.authentication.ClerkAuthentication",
# "rest_framework.authentication.SessionAuthentication", # optional fallback
),
}
4. Configure Clerk settings
# Required
CLERK_SECRET_KEY = "sk_test_..."
# Optional
CLERK_AUTH_PARTIES = ["http://localhost:3000", "https://your-app.com"]
CLERK_AUDIENCE = ["your-api-audience"] # passed to Clerk AuthenticateRequestOptions
CLERK_JWT_KEY = "..." # optional Clerk JWT verification key
CLERK_API_URL = "https://api.clerk.com" # custom Clerk API base URL
CLERK_TIMEOUT_MS = 5000
CLERK_CLOCK_SKEW_IN_MS = 5000
CLERK_CACHE_TIMEOUT = 300 # seconds
Authentication Behavior
Token sources checked by this SDK:
Authorization: Bearer <token>header- Clerk session cookie names starting with
__session
Flow:
- Extract token from header/cookie.
- Check cache (
sha256(token)-based key). - If cache miss, call Clerk
authenticate_request(...). - If signed in, fetch Clerk user details and sync into Django user.
- Save user PK in cache and return authenticated Django user.
When Clerk credentials are missing, middleware does not override an existing session-authenticated request.user.
User Synchronization Rules
ClerkClient.sync_django_user(...):
- Finds existing users by
clerk_user_idfirst, then by case-insensitive email. - Creates a new user if none exists.
- Syncs supported fields when present on your model:
clerk_user_id,email,username,first_name,last_name,image,last_active_at,is_active
- Converts
last_active_atUNIX timestamps (seconds or milliseconds) to timezone-aware UTC datetimes. - Deduplicates usernames (
name,name-2,name-3, ...). - Sets unusable password on newly created users when available.
If your custom user model omits some fields, only available fields are updated.
Public API
from django_clerk_sdk.core.auth.clerk import (
ClerkAuthentication,
ClerkClient,
ClerkMiddleware,
clerk_client,
)
Direct client usage:
from django_clerk_sdk.core.auth.clerk.sdk import clerk_client
state = clerk_client.authenticate_request(request)
user_id = clerk_client.get_user_id(state)
clerk_user = clerk_client.get_user_details(user_id)
django_user = clerk_client.sync_django_user(clerk_user)
Signals
from django_clerk_sdk.core.signals import (
clerk_auth_success,
clerk_auth_failed,
clerk_cache_miss,
)
Emitted events:
clerk_auth_success:user,source("cache"or"api")clerk_auth_failed:reason,token_hashclerk_cache_miss:token_hash
Example:
from django.dispatch import receiver
from django_clerk_sdk.core.signals import clerk_auth_success, clerk_auth_failed
@receiver(clerk_auth_success)
def on_clerk_auth_success(sender, user, source, **kwargs):
print(f"Clerk auth success for {user.pk} via {source}")
@receiver(clerk_auth_failed)
def on_clerk_auth_failed(sender, reason, token_hash, **kwargs):
print(f"Clerk auth failed ({reason}) token={token_hash}")
Notes
- The package exposes a script entry point (
django-clerk-sdk) only to explain that this is a library package, not a standalone CLI. - Minimum Python version is currently
3.14per package metadata.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_clerk_sdk-1.0.0.tar.gz.
File metadata
- Download URL: django_clerk_sdk-1.0.0.tar.gz
- Upload date:
- Size: 12.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
02edf186223b58eb67634d0820c5bb66c5eba33a991cb6bf8918776a38dddb3c
|
|
| MD5 |
f7f12deb0147716847b9ef6f63c5ec09
|
|
| BLAKE2b-256 |
927949c575c11b142eadca311c6a69a409281e819bc14b8ec75ff1192c10e10c
|
File details
Details for the file django_clerk_sdk-1.0.0-py3-none-any.whl.
File metadata
- Download URL: django_clerk_sdk-1.0.0-py3-none-any.whl
- Upload date:
- Size: 20.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.9.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5d3083b99e237a8478b3959327426a9d0cdfc05a466dcd46023e162a52b37ea8
|
|
| MD5 |
ef1161812137f6ae40ba827cc86ad1de
|
|
| BLAKE2b-256 |
3c64ff005e1568a1e8f40d42986a77f7b1e16e330c3edf0beb43a2e04046caad
|