Tutorial

Django allauth Setup: Email Login, Google, MFA, Passkeys

Set up django-allauth step by step: email login with code verification, Google login, custom signup forms, MFA and passkeys, plus my pick vs Clerk and NextAuth.

Key takeaways

  • Install django-allauth with pip, add three apps and one middleware to settings, include its URLs under /accounts/ and migrate. Do it after your custom user model exists.
  • My pick: use it for any server-rendered Django app, with email login, mandatory verification and a code instead of a link. Writing your own auth flows is a cost you don't need to pay.
  • Turn on TOTP MFA for everyone and security keys for staff. Enable passkey signup only if you can test it on your target browsers.
  • Pin the version and read the release notes before every upgrade. Check for deprecated settings and run migrations on a copy of production data.

django-allauth is an integrated set of Django apps for login, signup, account management and social login. To get it running, install it with pip, add three apps and one middleware to settings, include its URLs and migrate. We cover all of it below, step by step.

My pick: use it for server-rendered Django apps, with email login and mandatory verification. If you serve a SPA or mobile client, the headless app covers that too.

django-allauth in short, and my recommendation

django-allauth is an integrated set of Django applications for authentication, registration, account management and third-party social account authentication. That is how the project describes itself on GitHub. The allauth.account app handles regular accounts, meaning an email address or username plus a password.

I recommend it for any server-rendered Django app. Log in by email, make verification mandatory, and send a code instead of a link. Writing your own auth flows is a cost you don't need to pay.

If you are still choosing a framework, see Flask or Django: My Pick for Each Kind of Project.

What you need before you start

You need a working Django project, a custom user model in place before the first migrate, and an email backend. Changing the user model after migrations exist is painful, so decide now, even if the model is an empty subclass of AbstractUser.

  • A Django project on a Python and Django version that your allauth release supports (check the release notes).
  • A custom user model set in AUTH_USER_MODEL before the first migrate.
  • An email backend: SMTP in production, the console backend in development.
  • A Google OAuth client ID and secret, only if you add social login.
# settings.py (development)
AUTH_USER_MODEL = "accounts.User"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"

The console backend prints every email to the terminal running runserver. That is how you will read verification codes later.

Step 1: Install django-allauth

Install it with pip and the socialaccount extra, then pin the version. The library has to be installed separately before any of its features are available.

pip install "django-allauth[socialaccount]"
pip freeze | grep -i allauth

Copy the resulting version into your requirements file with an exact pin, for example the line below.

# requirements.txt
django-allauth[socialaccount]==65.3.1

Pin it because the project uses a loose form of semantic versioning. Its release notes warn that feature releases may occasionally include minor documented backwards incompatibilities, and say to always read the notes before upgrading.

Step 2: Add the apps, middleware and backends to settings

Add allauth, allauth.account and allauth.socialaccount to INSTALLED_APPS, the account middleware to MIDDLEWARE, and allauth's backend to AUTHENTICATION_BACKENDS. Keep Django's ModelBackend too so the admin still works.

# settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.google",
    "accounts",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "allauth.account.middleware.AccountMiddleware",
]

AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

SITE_ID = 1  # only if you use django.contrib.sites

Do you need the sites framework? Skip it for a single-domain app. Allauth offers optional support for it, which its README says helps larger multi-domain projects and makes switching between a localhost and production setup easy. If you run several domains, add django.contrib.sites and SITE_ID.

Step 3: Wire up URLs and run migrations

Include allauth.urls under an accounts/ prefix, then run migrate. Do the migrate only after your custom user model exists.

# urls.py
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
    path("accounts/", include("allauth.urls")),
]
python manage.py makemigrations
python manage.py migrate
python manage.py runserver

This gives you these pages under /accounts/:

  • /accounts/login/ for login
  • /accounts/signup/ for registration
  • /accounts/logout/ for logout
  • /accounts/password/reset/ for the password-forgotten flow
  • /accounts/email/ for email address management
  • /accounts/password/change/ for changing the password

Behind these pages the account app supports an email verification flow, password changes and a simple or multi-address email change flow, covering what most apps need.

Step 4: Choose the login method and email verification

Log in by email, make verification mandatory, and verify by code. Here are the settings I recommend.

# settings.py
ACCOUNT_LOGIN_METHODS = {"email"}
ACCOUNT_SIGNUP_FIELDS = ["email*", "password1*", "password2*"]
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True
ACCOUNT_LOGIN_BY_CODE_ENABLED = True
# Require a code on every login (optional, stricter):
# ACCOUNT_LOGIN_BY_CODE_REQUIRED = True
ACCOUNT_EMAIL_NOTIFICATIONS = True

Allauth can verify addresses with a code instead of a link through ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED. It can also require every user to enter an emailed login code through ACCOUNT_LOGIN_BY_CODE_REQUIRED. I enable the first by default and the second only when the app handles sensitive data.

Rate limits replace the old settings

ACCOUNT_LOGIN_ATTEMPTS_LIMIT and ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN are deprecated. Use ACCOUNT_RATE_LIMITS instead. Rules now say whether a limit applies per user, IP address or key, and you can combine scopes.

ACCOUNT_RATE_LIMITS = {
    "login_failed": "10/m/ip,5/5m/key",
    "confirm_email": "1/3m/key",
}

The values above are my example numbers, so tune them. Rate limiting depends on knowing the client IP, which Django can't reliably determine on its own. Allauth now distrusts X-Forwarded-For by default, so behind a proxy set ALLAUTH_TRUSTED_PROXY_COUNT, rely on ALLAUTH_TRUSTED_CLIENT_IP_HEADER, or override get_client_ip(). IPv6 addresses are truncated to a /64 prefix by default, configurable with ALLAUTH_RATE_LIMIT_IPV6_PREFIX.

One more detail: email addresses are now always stored in lowercase, with migrations for existing records. Don't compare against mixed-case addresses in your own queries.

Step 5: Add Google social login

Configure Google in SOCIALACCOUNT_PROVIDERS in settings.py, then register the callback URL with Google. I prefer settings over a SocialApp row in the admin because credentials live in version-controlled config and environment variables, and every environment gets the same setup without manual admin clicks.

# settings.py
import os

SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "APPS": [
            {
                "client_id": os.environ["GOOGLE_CLIENT_ID"],
                "secret": os.environ["GOOGLE_CLIENT_SECRET"],
                "key": "",
            }
        ],
        "SCOPE": ["profile", "email"],
        "AUTH_PARAMS": {"access_type": "online"},
    }
}

Step 6: Customise the signup form and behaviour

Use ACCOUNT_SIGNUP_FORM_CLASS to add fields, ACCOUNT_FORMS to replace a form, and the adapter for behaviour. Allauth's maintainers say to configure ACCOUNT_SIGNUP_FORM_CLASS to add fields to the built-in form, rather than ACCOUNT_FORMS.

# accounts/forms.py
from django import forms


class CustomSignupForm(forms.Form):
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)

    def signup(self, request, user):
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]
        user.save()
# settings.py
ACCOUNT_SIGNUP_FORM_CLASS = "accounts.forms.CustomSignupForm"

When to subclass the adapter

Subclass the account adapter when you want to change behaviour rather than fields. The project says its adapter pattern lets you intervene at chosen points to change standard behaviour. A maintainer pointed to is_login_by_code_required() as the method to override to require login-by-code selectively.

# accounts/adapters.py
from allauth.account.adapter import DefaultAccountAdapter


class AccountAdapter(DefaultAccountAdapter):
    def is_login_by_code_required(self, login):
        # example logic: require a code only for staff users
        return bool(getattr(login.user, "is_staff", False))
# settings.py
ACCOUNT_ADAPTER = "accounts.adapters.AccountAdapter"
Option What it changes When I use it
ACCOUNT_SIGNUP_FORM_CLASS Adds fields to the existing built-in signup form Almost always: extra fields like a name
ACCOUNT_FORMS Completely swaps out a form Only when the built-in form's layout or logic must be replaced
Custom account adapter Behaviour, such as whether login-by-code is required Rules that depend on the user or request

Step 7: Turn on MFA and passkeys

Add allauth.mfa to INSTALLED_APPS and enable the TOTP authenticator type. Then set a tolerance for clock drift with MFA_TOTP_TOLERANCE, which allauth supports for TOTP code tolerance.

# settings.py
INSTALLED_APPS += ["allauth.mfa"]

MFA_SUPPORTED_TYPES = ["totp", "recovery_codes"]
MFA_TOTP_TOLERANCE = 1  # accept codes one step either side

Run python manage.py migrate again after adding the app. Users then enrol from the MFA pages under the same /accounts/ prefix.

WebAuthn and passkeys

Allauth added WebAuthn security keys and passkey login, and they are disabled by default. Passkey signup has its own switch, MFA_PASSKEY_SIGNUP_ENABLED. Newer releases also let you control user verification for WebAuthn with MFA_WEBAUTHN_USER_VERIFICATION.

MFA_SUPPORTED_TYPES = ["totp", "recovery_codes", "webauthn"]
MFA_PASSKEY_LOGIN_ENABLED = True
MFA_PASSKEY_SIGNUP_ENABLED = True

My view: turn on TOTP now for everyone, and enable security keys for staff accounts. Enable passkey signup only if you can test it on your target browsers, since it changes the first thing a new user sees.

What you end up with and how to check it works

You end up with email signup and login, code verification, password reset, optional Google login and MFA, all running at /accounts/. Test each flow against the dev server with the console email backend, reading codes from the terminal.

  1. Open /accounts/signup/ and register with an email address.
  2. Copy the verification code from the console output and enter it.
  3. Log out at /accounts/logout/, then log in at /accounts/login/.
  4. If login-by-code is on, read the login code from the console.
  5. Request a reset at /accounts/password/reset/ and follow the emailed link.
  6. Click the Google button on the login page and finish the consent screen.
  7. Enrol an authenticator app in the MFA pages, then log in again to confirm the prompt.

With ACCOUNT_EMAIL_NOTIFICATIONS = True, users also get security emails such as "Your password was changed", including the user agent and IP address the change came from. You will see these in the console after the password reset step.

Using allauth with a SPA, mobile app or FastAPI

For single-page and mobile apps, use the allauth.headless app, the official API for those clients. It arrived in the 2024 releases.

INSTALLED_APPS += ["allauth.headless"]
HEADLESS_ONLY = False  # keep regular pages too (hybrid)

In a hybrid setup, headless signup inputs inherit the custom signup form class you configured for regular signup, so your extra fields carry over. For mobile and other non-browser consumers, use the app client, which uses session tokens.

Sharing the database with FastAPI

In a shared schema, let Django own the auth tables. Our guide on database migrations in a Django and FastAPI shared-schema setup recommends that split. If FastAPI needs to read one, define it as a read-only SQLAlchemy model.

# FastAPI / SQLAlchemy: read-only mirror of Django's auth table
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()


class User(Base):
    __tablename__ = "auth_user"  # use your custom model's table name
    id = Column(Integer, primary_key=True)
    email = Column(String)

With a custom user model, point __tablename__ at that model's table, such as accounts_user. Never write to it from FastAPI.

Upgrading django-allauth without surprises

Upgrade deliberately: pin the version, read the release notes, then test. Read the notes before every feature release, because the project documents minor backwards incompatibilities there.

  1. Bump the pinned version in a branch.
  2. Read the release notes for every version you skip.
  3. Run your tests with warnings on and look for deprecated settings such as ACCOUNT_LOGIN_ATTEMPTS_LIMIT.
  4. Run python manage.py migrate on a copy of production data to exercise the lowercase-email migration.
  5. Repeat the signup, login and reset checks from the checklist.

Stay current for security reasons too. A past release fixed email and password authentication being vulnerable to account enumeration through a timing attack, and the project advertises enumeration prevention as a feature.

Decision table: allauth or something else

Pick allauth for Django apps where you want to own user data, and pick a hosted service when your frontend isn't Django. We have walked through both alternatives for a Django, FastAPI and Next.js stack: Clerk and Next-Auth.

Option Best project type Social login MFA Cost Who owns user data
django-allauth Server-rendered Django, or Django API via headless Yes, via providers such as Google Yes, via allauth.mfa Free library, you host it You, in your database
Django built-in auth Simple internal tools Not included Not included Free You
Clerk Next.js-first apps that want a hosted service Hosted Hosted Vendor pricing Vendor holds it, synced to you
NextAuth Next.js apps with their own backend Provider-based You build it Free library You

My picks: allauth for Django-first products, built-in auth only for throwaway tools, Clerk when speed in a Next.js frontend matters more than owning the data, and NextAuth when Next.js is the center of the app.

Frequently asked questions

Does django-allauth work with a single-page app or mobile app?

Yes. The allauth.headless app is the official API for single-page and mobile applications. Use its app client with session tokens for mobile.

Can email be used as a second factor in django-allauth?

Not as an MFA method. A maintainer said email isn't a true second factor, because password reset and an emailed login code both depend on control of the same mailbox. If you want a code on login, use login-by-code instead.

Should I set up a custom user model before installing django-allauth?

Yes. Set AUTH_USER_MODEL before the first migrate, because switching later means reworking migrations. An empty subclass of AbstractUser is enough.

What should I check before upgrading django-allauth?

Read the release notes, since feature releases may include minor documented backwards incompatibilities. Then check for deprecated settings and run the migrations on a copy of your data.

Sources

  1. django-allauth, docs.allauth.org
  2. GitHub - pennersr/django-allauth: Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication. 🔁 Mirror of https://codeberg.org/allauth/django-allauth/ · GitHub, github.com
  3. Introduction — django-allauth 64.3.0 documentation, django-allauth.readthedocs.io
  4. django-modern-rest/docs/pages/auth/allauth.rst at master · wemake-services/django-modern-rest · GitHub, github.com
  5. 65.3.1 (2024-12-25) - django-allauth, docs.allauth.org
  6. python - AssertionError in django-allauth settings.py during Django application startup - Stack Overflow, stackoverflow.com
  7. 65.21.1 (2026-10-30) - django-allauth, docs.allauth.org
  8. #3934 - Extend SignupInput with custom fields in allauth.headless - allauth/django-allauth - Codeberg.org, codeberg.org
  9. #4181 - Email as MFA method - allauth/django-allauth - Codeberg.org, codeberg.org