Skip to main content

Drop-in multifactor authentication subsystem for Django.

Project description

django-multifactor - Easy multi-factor authentication for Django

Code Style Pre-Commit Enabled

Probably the easiest multi-factor for Django. Ships with standalone views, opinionated defaults and a very simple integration pathway to retrofit onto mature sites. Supports FIDO2/WebAuthn and TOTP authenticators, with removable fallback options for email, SMS, carrier pigeon, or whatever other token exchange you can think of. U2F has been removed in 0.6.

This is not a passwordless authentication system. django-multifactor is a second layer of defence.

PyPI version

FIDO2/WebAuthn is the big-ticket item for MFA. It allows the browser to interface with a myriad of biometric and secondary authentication factors.

  • Security keys (Firefox 60+, Chrome 67+, Edge 18+),
  • Windows Hello (Firefox 67+, Chrome 72+ , Edge) ,
  • Apple's Touch ID (Chrome 70+ on Mac OS X ),
  • android-safetynet (Chrome 70+)
  • NFC devices using PCSC (Not Tested, but as supported in fido2)

Python and Django Support

This project targets modern stacks, officially supporting Python 3.10+ and Django 5.2+. Please refer to the Django documentation for more

Python/Django 5.2 6.0 6.1
3.10 Y N/A N/A
3.11 Y N/A N/A
3.12 Y Y Y
3.13 Y Y Y
3.14 Y (5.2.8+) Y Y
3.15 Y (5.2.8+) Y Y

If you are using an older version of Django or Python please consider upgrading your project, alternatively you can use Version 0.8.4 which the supports Django 2.2 - 5.2, with Python 3.8 - 3.13

Installation:

Install the package:

pip install django-multifactor

Add multifactor to settings.INSTALLED_APPS and override whichever setting you need.

MULTIFACTOR = {
    'LOGIN_CALLBACK': False,             # False, or dotted import path to function to process after successful authentication
    'RECHECK': True,                     # Invalidate previous authorisations at random intervals
    'RECHECK_MIN': 60 * 60 * 3,          # No rechecks before 3 hours
    'RECHECK_MAX': 60 * 60 * 6,          # But within 6 hours

    'FIDO_SERVER_ID': 'example.com',     # Server ID for FIDO request
    'FIDO_SERVER_NAME': 'Django App',    # Human-readable name for FIDO request
    'TOKEN_ISSUER_NAME': 'Django App',   # TOTP token issuing name (to be shown in authenticator)
    
    # Optional Keys - Only include these keys if you wish to deviate from the default actions
    'LOGIN_MESSAGE': '<a href="{}">Manage multifactor settings</a>.',  # {OPTIONAL} When set overloads the default post-login message.
    'SHOW_LOGIN_MESSAGE': False,  # {OPTIONAL} <bool> Set to False to not create a post-login message
}

Ensure that django.contrib.messages is installed.

Include multifactor.urls in your URLs. You can do this anywhere but I suggest somewhere similar to your login URLs, or underneath them, eg:

urlpatterns = [
    path('admin/multifactor/', include('multifactor.urls')),
    path('admin/', admin.site.urls),
    ...
]

And don't forget to run a ./manage.py collectstatic before restarting Django.

Usage

At this stage any authenticated user can add a secondary factor to their account by visiting (eg) /admin/multifactor/, but no view will require secondary authentication. django-multifactor gives you granular control to conditionally require certain users need a secondary factor on certain views. This is accomplished through the multifactor.decorators.multifactor_protected decorator.

from multifactor.decorators import multifactor_protected

@multifactor_protected(factors=0, user_filter=None, max_age=0, advertise=False)
def my_view(request):
    ...
  • factors is the minimum number of active, authenticated secondary factors. 0 will mean users will only be prompted if they have keys. It can also accept a lambda/function with one request argument that returns a number. This allows you to tune whether factors are required based on custom logic (eg if local IP return 0 else return 1)
  • user_filter can be a dictionary to be passed to User.objects.filter() to see if the current user matches these conditions. If empty or None, it will match all users.
  • max_age=600 will ensure the the user has authenticated with their secondary factor within 10 minutes. You can tweak this for higher security at the cost of inconvenience.
  • advertise=True will send an info-level message via django.contrib.messages with a link to the main django-multifactor page that allows them to add factors for future use. This is useful to increase optional uptake when introducing multifactor to an organisation.

You can also wrap entire branches of your URLs using django-decorator-include:

from decorator_include import decorator_include
from multifactor.decorators import multifactor_protected

urlpatterns = [
    path('admin/multifactor/', include('multifactor.urls')),
    path('admin/', decorator_include(multifactor_protected(factors=1), admin.site.urls)),
    ...
]

Don't want to allow TOTP? Turn them off.

You can control the factors users can pick from in settings.MULTIFACTOR:

MULTIFACTOR = {
    # ...
    'FACTORS': ['FIDO2', 'TOTP'],  # <- this is the default
}

Extending OTP fallback with custom transports

django-multifactor has a fallback system that allows the user to be contacted via a number of sub-secure methods simultaneously. The rationale is that if somebody hacks their email account, they'll still know something is going on when they get an SMS. Providing sane options for your users is critical to security here. A poor fallback can undermine otherwise solid factors.

The included fallback uses user.email to send an email. This now sends as plain+HTML. You can send just plain by setting settings.MULTIFACTOR.HTML_EMAIL to False.

You can plumb in additional functions to carry the OTP message over any other system you like. The function should look something like:

def send_carrier_pigeon(user, message):
    bird = find_bird()
    bird.attach(message)
    bird.send(user.address)
    return True  # to indicate it sent

Then hook that into settings.MULTIFACTOR:

MULTIFACTOR = {
    # ...
    'FALLBACKS': {
        'email': (lambda user: user, 'multifactor.factors.fallback.send_email'),
        'pigeon': (lambda user: user.address, 'path.to.send_carrier_pigeon'),
    }
}

Now if the user selects the fallback option, they will receive an email and a pigeon. You can remove email by omitting that line. You can disable fallback entirely by setting FALLBACKS to an empty dict.

Conditional bypass

It's sometimes useful to be able to be able to conditionally bypass multifactor requirements. You might be in local testing, you might be in automated testing or impersonating other users. Deactivating a security layer has obvious risks but that's between you and your gods.

settings.MULTIFACTOR.BYPASS accepts a single path to a function accepting a request. If that returns True, multifactor will bypass its normal checks on a page.

MULTIFACTOR = {
    # ...
    'BYPASS': 'path.to.bypass_when_impersonating'
}

These are relatively easy to implement:

def bypass_when_impersonating(request):
    from loginas.utils import is_impersonated_session
    if is_impersonated_session(request):
        return True

def bypass_when_debug(request):
    from django.config import settings
    return settings.DEBUG

UserAdmin integration

It's often useful to monitor which of your users is using django-multifactor and, in emergencies, critical to be able to turn their secondary factors off. We ship a opinionated mixin class that you can add to your existing UserAdmin definition.

from multifactor.admin import MultifactorUserAdmin

@admin.register(User)
class StaffAdmin(UserAdmin, MultifactorUserAdmin):
    ...

It adds a column to show if that user has active factors, a filter to just show those with or without, and an inline to allow admins to turn certain keys off for their users.

Branding

If you want to use the styles and form that django-multifactor supplies, your users may think they're on another site. To help there is an empty placeholder template multifactor/brand.html that you can override in your project. This slots in just before the h1 title tag and has text-align: centre as standard.

If you use HTML emails for your email fallback, you can create a multifactor/email.html template (accepting user, message context variables).

You can use this to include your product logo, or an explanation.

Internationalisation (i18n)

All user-facing strings in views, templates, model labels and flash messages are wrapped for translation, and the package ships compiled .mo files in the wheel. You do not need to run makemessages or compilemessages against this app in your own project.

To take advantage of the translations in your project:

  1. Enable Django's i18n machinery in settings.py (these are Django defaults but worth confirming):

    USE_I18N = True
    LANGUAGE_CODE = "en"  # or your preferred default
    
  2. If you want the language to switch per-request (based on the Accept-Language header, a session value, or a cookie), add LocaleMiddleware after SessionMiddleware and before CommonMiddleware:

    MIDDLEWARE = [
        # ...
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.locale.LocaleMiddleware",
        "django.middleware.common.CommonMiddleware",
        # ...
    ]
    
  3. The default LOGIN_MESSAGE setting is a translatable string. If you override MULTIFACTOR['LOGIN_MESSAGE'] with your own text and want it translated, wrap it with gettext_lazy:

    from django.utils.translation import gettext_lazy as _
    
    MULTIFACTOR = {
        # ...
        "LOGIN_MESSAGE": _('<a href="{}">Manage multifactor settings</a>.'),
    }
    

Bundled languages

Locale Status
en Source (default)

If you have translated django-multifactor into another language, PRs are very welcome — see Contributing translations below.

Contributing translations

Translations live in multifactor/locale/<language>/LC_MESSAGES/django.po. To add a new language (e.g. French):

  1. Clone the repo and install dev dependencies.

  2. From the multifactor/ directory, generate the catalog for your locale:

    cd multifactor
    django-admin makemessages -l fr
    
  3. Translate the entries in multifactor/locale/fr/LC_MESSAGES/django.po.

  4. Compile the catalog so the .mo file is up-to-date:

    django-admin compilemessages
    
  5. Commit both django.po and django.mo and open a PR.

If you change any source strings, re-run makemessages -a (across all locales) and compilemessages before releasing so the bundled .mo files stay in sync with the source.

Contributing

This project welcomes contributions to submit PRs and issues.

This project supports pre-commit hooks to re-format code using black and isort.

To install pre-commit run pip install pre-commit then pre-commit install.

To update the pre-commit-config.yaml run pre-commit autoupdate.

To run pre-commit hooks againt all files run pre-commit run --all-files.

To contribute translations please see the [Contributing translations](#Contributing translations) section

Testing

This project uses tox for testing. Install tox via pip and run tox to run the tests.

Flowchart

flowchart TD
    Start([User attempts to access protected page]) --> Auth{User authenticated?}
    
    Auth -->|No| AllowAccess[Allow access - no MFA required]
    Auth -->|Yes| Bypass{Bypass enabled?}
    
    Bypass -->|Yes| AllowAccess
    Bypass -->|No| UserFilter{User matches filter?}
    
    UserFilter -->|No filter set or<br/>user matches| CheckKeys{User has<br/>MFA keys?}
    UserFilter -->|User doesn't match| AllowAccess
    
    CheckKeys -->|No keys| CheckRequired{factors > 0?}
    CheckKeys -->|Has keys| CheckActive{Keys authenticated<br/>in session?}
    
    CheckRequired -->|No| Advertise{advertise=true?}
    CheckRequired -->|Yes| RequireAuth[Redirect to authenticate]
    
    Advertise -->|Yes| ShowMessage[Show optional MFA message]
    Advertise -->|No| AllowAccess
    ShowMessage --> AllowAccess
    
    CheckActive -->|No| RequireAuth
    CheckActive -->|Yes| CheckAge{max_age set?}
    
    CheckAge -->|No| CheckFactorCount
    CheckAge -->|Yes| AgeValid{Auth timestamp<br/>within max_age?}
    
    AgeValid -->|No| ShowWarning[Show re-auth warning]
    AgeValid -->|Yes| CheckFactorCount{Active factors >=<br/>required factors?}
    
    ShowWarning --> RequireAuth
    
    CheckFactorCount -->|No| ShowFactorWarning[Show factor count warning]
    CheckFactorCount -->|Yes| AllowAccess
    
    ShowFactorWarning --> RequireAuth
    
    RequireAuth --> AuthPage[MFA Authentication Page]
    
    AuthPage --> SelectMethod{Select auth method}
    
    SelectMethod -->|FIDO2| FIDO2Auth[Authenticate with<br/>Security Key/Biometric]
    SelectMethod -->|TOTP| TOTPAuth[Enter TOTP code<br/>from Authenticator]
    SelectMethod -->|Fallback| FallbackAuth[Send OTP via<br/>email/SMS/custom]
    
    FIDO2Auth --> Verify{Verification<br/>successful?}
    TOTPAuth --> Verify
    FallbackAuth --> Verify
    
    Verify -->|No| AuthPage
    Verify -->|Yes| WriteSession[Write auth to session<br/>with timestamp]
    
    WriteSession --> Recheck{RECHECK enabled?}
    
    Recheck -->|Yes| SetExpiry[Set random expiry<br/>between MIN and MAX]
    Recheck -->|No| SetNever[Set no expiry]
    
    SetExpiry --> Redirect[Redirect to original page]
    SetNever --> Redirect
    
    Redirect --> Start
    
    AllowAccess --> Done([Access granted])
    
    style Start fill:#e1f5ff
    style Done fill:#d4edda
    style RequireAuth fill:#fff3cd
    style AllowAccess fill:#d4edda
    style AuthPage fill:#cfe2ff
    style WriteSession fill:#cfe2ff

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

django_multifactor-0.9.0.tar.gz (54.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_multifactor-0.9.0-py3-none-any.whl (66.6 kB view details)

Uploaded Python 3

File details

Details for the file django_multifactor-0.9.0.tar.gz.

File metadata

  • Download URL: django_multifactor-0.9.0.tar.gz
  • Upload date:
  • Size: 54.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.4.1 CPython/3.11.0 Linux/6.17.0-1018-azure

File hashes

Hashes for django_multifactor-0.9.0.tar.gz
Algorithm Hash digest
SHA256 c50edae79203ef56f00c2b4ad876fea9f92a02d0460430faee7731e99dd5ec56
MD5 b697e6cef89c6d9556deefd183ad7857
BLAKE2b-256 0f0df5b98db39ab6edfe8eda4fde2aa32ccb937e10a5041e7cff06d2a1d10cab

See more details on using hashes here.

File details

Details for the file django_multifactor-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: django_multifactor-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 66.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.4.1 CPython/3.11.0 Linux/6.17.0-1018-azure

File hashes

Hashes for django_multifactor-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1aefc829bf7046d1bbe2c22ce740539bfb205c7740f436c063b598aa6e119ae5
MD5 94020f7d37fdc7e55b080182d01b9e7b
BLAKE2b-256 204e785bf8e0976d4cf4b61b064faa105fa0a1b6071b290bb60ababdb6c4bc83

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page