xiaohongshu
xiaohongshu
django-allauth
Configure django-allauth with headless API, MFA, social authentication, and CORS for React frontends. This skill should be used when setting up authentication for a new Django project or adding django-allauth to an existing project that needs a React frontend integration. (project)
Full skill instructions
This skill configures django-allauth in headless mode for React/Vue/frontend applications. Unlike traditional Django authentication that renders server-side templates, headless mode exposes authentication as REST APIs, making it ideal for single-page applications (SPAs) and mobile apps.
What this skill provides:
End result: A Django backend with secure, production-ready authentication APIs that the React frontend can consume via HTTP requests.
Before using this skill, ensure:
To set up django-allauth in headless mode for React, follow these steps:
settings.py.env.developmenturls.pyInstall the required packages for authentication, social login, MFA, and cross-origin requests:
source venv/bin/activate
pip install 'django-allauth[socialaccount,mfa]' python-dotenv djangorestframework django-cors-headers fido2 python3-openid Pillow pyyaml
Package purposes:
django-allauth[socialaccount,mfa] - Core authentication with social providers and multi-factor authpython-dotenv - Load environment variables from .env filesdjangorestframework - REST API framework (required by allauth headless)django-cors-headers - Enable cross-origin requests from React frontendfido2 - WebAuthn/passkey support for passwordless authenticationpython3-openid - OpenID authentication support for social providersPillow - Image processing library (required for avatar/profile images)pyyaml - YAML parser (required for allauth configuration)settings.pyEditing steps for settings.py:
Insert these lines at the end of the existing imports (top of the file):
import os
from dotenv import load_dotenv
load_dotenv('.env.development')
Why: Django-allauth requires access to the request object in templates for authentication flows.
Find TEMPLATES[0]['OPTIONS']['context_processors'] and check if this line exists in the list:
'django.template.context_processors.request',
If missing: Add it to the end of the context_processors list
Find the INSTALLED_APPS list and append the following to the end of the list:
# Authentication and user management (django-allauth)
'allauth',
'allauth.account',
'allauth.socialaccount',
# Providers
'allauth.socialaccount.providers.google',
# Multi-Factor Authentication (MFA)
'allauth.mfa',
# Headless API support for allauth
'allauth.headless',
'allauth.usersessions',
The end result should look similar to:
INSTALLED_APPS = [
# Django core apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Cross-Origin Resource Sharing
'corsheaders',
# REST API support
'rest_framework',
# Authentication and user management (django-allauth)
'allauth',
'allauth.account',
'allauth.socialaccount',
# Providers
'allauth.socialaccount.providers.google',
# Multi-Factor Authentication (MFA)
'allauth.mfa',
# Headless API support for allauth
'allauth.headless',
'allauth.usersessions',
]
Find the MIDDLEWARE list. After 'django.contrib.messages.middleware.MessageMiddleware',, add:
"allauth.account.middleware.AccountMiddleware",
Critical middleware order requirements:
CorsMiddleware must come AFTER SessionMiddleware and BEFORE CommonMiddleware to properly handle CORS headers before request processingAccountMiddleware must come AFTER MessageMiddleware to access session-based authentication stateExpected result:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'allauth.account.middleware.AccountMiddleware', # ← Add here
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Location: At the very end of settings.py
Action: Append all of the following authentication and MFA configuration:
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
]
# Account settings
ACCOUNT_EMAIL_VERIFICATION = "mandatory" # Require email verification before login
ACCOUNT_LOGIN_METHODS = {'email'} # Use email instead of username for login
ACCOUNT_SIGNUP_FIELDS = ['email*', 'password1*', 'password2*']
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = False
ACCOUNT_LOGIN_BY_CODE_ENABLED = True # Enable passwordless login via email code
ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
# Multi-Factor Authentication settings
MFA_SUPPORTED_TYPES = ["totp", "webauthn", "recovery_codes"]
MFA_PASSKEY_LOGIN_ENABLED = True # Enable passwordless WebAuthn login
MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = True if DEBUG else False # Allow localhost in dev
MFA_PASSKEY_SIGNUP_ENABLED = True
# Headless mode configuration
HEADLESS_ONLY = True # Disable server-side templates, use API endpoints only
HEADLESS_FRONTEND_URLS = {
"account_confirm_email": f"{FRONTEND_URL}/account/verify-email/{{key}}",
"account_reset_password": f"{FRONTEND_URL}/account/password/reset",
"account_reset_password_from_key": f"{FRONTEND_URL}/account/password/reset/key/{{key}}",
"account_signup": f"{FRONTEND_URL}/account/signup",
"socialaccount_login_error": f"{FRONTEND_URL}/account/provider/error",
}
# Provider specific settings
SOCIALACCOUNT_PROVIDERS = {
'google': {
'APP': {
'client_id': os.environ.get('GOOGLE_CLIENT_ID'),
'secret': os.environ.get('GOOGLE_CLIENT_SECRET'),
'key': ''
},
'FETCH_USERINFO': True,
}
}
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = BASE_DIR / 'sent_emails'
Key configuration notes:
HEADLESS_ONLY = True disables Django's template-based authentication views and forces API-only modeHEADLESS_FRONTEND_URLS tells the backend where to redirect users in email links (e.g., password reset, email verification)SOCIALACCOUNT_PROVIDERS as neededLocation: Project root (same directory as manage.py)
File: .env.development
Action: Create file with OAuth credentials (leave empty for now, fill in when setting up social auth):
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
If file exists: Only add missing keys, don't overwrite existing values
urls.pyLocation: Django project package (same directory as settings.py)
First add include to imports and then add allauth URLs in urls.py:
path('accounts/', include('allauth.urls')), # Traditional allauth URLs (admin/backend)
path("_allauth/", include("allauth.headless.urls")), # Headless API endpoints for frontend
Why two URL patterns:
accounts/ - Django admin integration and backend management_allauth/ - RESTful API endpoints that the React frontend will callVerify that all settings are correctly configured before running migrations:
python manage.py check
Expected: No errors (warnings about unapplied migrations are OK)
Create the database tables for authentication, social accounts, and MFA:
python manage.py migrate
What this creates:
Verify the django-allauth installation by running the official test suite. This ensures all core functionality is working correctly.
If not already cloned, clone the official repository to access the test suite:
git clone https://github.com/pennersr/django-allauth.git
Install pytest and required testing packages:
pip install 'pytest>=7.4,<9.0' 'pytest-asyncio==0.23.8' pytest-django pytest-cov django-ninja
Note: Pytest 9.x has compatibility issues with the django-allauth test suite. Using pytest 8.x ensures all tests pass successfully.
pip freeze > requirements.txt
Use the validation script to run the core test suite at: scripts/validate_allauth_tests.sh
Success criteria: All 76 tests should pass
Test coverage:
These tests confirm that your installation properly supports:
If tests fail: Review the error messages. Common issues include:
settings.py configurationFor detailed test information: See references/test-validation-guide.md for:
rm -rf django-allauth
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience