Package: django-mfa2
django-mfa2A Django app that handles MFA, it supports TOTP, U2F, FIDO2 U2F (Web Authn), Email Tokens , Trusted  Devices and backup codes.Pip StatsConda StatsWeb Authencation API (WebAuthn) is state-of-the art techology that is expected to replace passwords.For FIDO2, the following are supportedsecurity keys(Firefox 60+, Chrome 67+, Edge 18+, Safari 13 on Mac OS, Chrome on Andriod, Safari on iOS 13.3+),Windows Hello(Firefox 67+, Chrome 72+ , Edge),Apple's Touch ID/Face ID(Chrome 70+ on Mac OS X, Safari on macOS Big Sur, Safari on iOS 14.0+ ),android-safetynet(Chrome 70+, Firefox 68+)NFC devices using PCSC(Not Tested, but as supported in fido2)Soft Tokenskrypt.co: Login by a notification on your phone.Update: Dec 2022, krypt.co has been killed by Google for Passkeys.In English :), It allows you to verify the user by security keys on PC, Laptops or Mobiles, Windows Hello (Fingerprint, PIN) on Windows 10 Build 1903+ (May 2019 Update) Touch/Face ID on Macbooks (Chrome, Safari), Touch/Face ID on iPhone and iPad and Fingerprint/Face/Iris/PIN on Android Phones.Trusted device is a mode for the user to add a device that doesn't support security keys like Android without fingerprints or NFC.Note:U2F and FIDO2 can only be served under secure context (https)Package tested with Django 1.8, Django 2.2 on Python 2.7 and Python 3.5+ but it was not checked with any version in between but open for issues.If you just need WebAuthn and Passkeys, you can usedjango-passkeys, which is a slim-down of this app and much easier to integrate.Depends onpyotppython-u2flib-serverua-parseruser-agentspython-josefido2==1.0.0Installationusing pipFor Django >= 4.0pip install django-mfa2For Django < 4.0pip install django-mfa2 jsonfieldUsing Conda forgeconda config --add channels conda-forgeconda install django-mfa2For more info, see the conda-forge repo (https://github.com/conda-forge/django-mfa2-feedstock)Thanks forswainnfor adding package to conda-forgeUsagein your settings.py add the application to your installed appsINSTALLED_APPS=('......','mfa','......')Collect Static Filespython manage.py collectstaticAdd the following settings to your filefromdjango.conf.global_settingsimportPASSWORD_HASHERSasDEFAULT_PASSWORD_HASHERS#Preferably at the same place where you import your other modulesMFA_UNALLOWED_METHODS=()# Methods that shouldn't be allowed for the user e.g ('TOTP','U2F',)MFA_LOGIN_CALLBACK=""# A function that should be called by username to login the user in sessionMFA_RECHECK=True# Allow random rechecking of the userMFA_REDIRECT_AFTER_REGISTRATION="mfa_home"# Allows Changing the page after successful registerationMFA_SUCCESS_REGISTRATION_MSG="Go to Security Home"# The text of the linkMFA_RECHECK_MIN=10# Minimum interval in secondsMFA_RECHECK_MAX=30# Maximum in secondsMFA_QUICKLOGIN=True# Allow quick login for returning users by provide only their 2FAMFA_ALWAYS_GO_TO_LAST_METHOD=False# Always redirect the user to the last method used to save a click (Added in 2.6.0).MFA_RENAME_METHODS={}#Rename the methods in a more user-friendly way e.g {"RECOVERY":"Backup Codes"} (Added in 2.6.0)MFA_HIDE_DISABLE=('FIDO2',)# Can the user disable his key (Added in 1.2.0).MFA_OWNED_BY_ENTERPRISE=FALSE# Who owns security keysPASSWORD_HASHERS=DEFAULT_PASSWORD_HASHERS# Comment if PASSWORD_HASHER already set in your settings.pyPASSWORD_HASHERS+=['mfa.recovery.Hash']RECOVERY_ITERATION=350000#Number of iteration for recovery code, higher is more secure, but uses more resources for generation and check...TOKEN_ISSUER_NAME="PROJECT_NAME"#TOTP Issuer nameU2F_APPID="https://localhost"#URL For U2FFIDO_SERVER_ID=u"localehost"# Server rp id for FIDO2, it is the full domain of your projectFIDO_SERVER_NAME=u"PROJECT_NAME"Method NamesU2FFIDO2TOTPTrusted_DevicesEmailRECOVERYNotes:Starting version 1.1,FIDO_LOGIN_URLisn't required for FIDO2 anymore.Starting version 1.7.0, Key owners can be specified.Starting version 2.2.0Added:MFA_SUCCESS_REGISTRATION_MSG&MFA_REDIRECT_AFTER_REGISTRATIONStart version 2.6.0Added:MFA_ALWAYS_GO_TO_LAST_METHOD,MFA_RENAME_METHODS,MFA_ENFORCE_RECOVERY_METHOD&RECOVERY_ITERATIONBreak your login functionUsually your login function will check for username and password, log the user in if the username and password are correct and create the user session, to support mfa, this has to changeauthenticate the userif username and password are correct , check if the user has mfa or notif user has mfa then redirect to mfa pageif user doesn't have mfa then call your function to create the user sessiondeflogin(request):# this function handles the login form POSTuser=auth.authenticate(username=username,password=password)ifuserisnotNone:# if the user object existfrommfa.helpersimporthas_mfares=has_mfa(username=username,request=request)# has_mfa returns false or HttpResponseRedirectifres:returnresreturnlog_user_in(request,username=user.username)#log_user_in is a function that handles creatung user session, it should be in the setting file as MFA_CALLBACKAdd mfa to urls.pyimportmfaimportmfa.TrustedDeviceurls_patterns=['...',url(r'^mfa/',include('mfa.urls')),url(r'devices/add$',mfa.TrustedDevice.add,name="mfa_add_new_trusted_device"),# This short link to add new trusted device'....',]Providemfa_auth_base.htmlin your templates with block called 'head' and 'content', The template will be included during the user login, the template shall be close to the login template.
If you will use Email Token method, then you have to provide template namedmfa_email_token_template.htmlthat will content the format of the email with parameter nameduserandotp.To match the look and feel of your project, MFA includesbase.htmlbut it needs blocks namedhead&contentto added its content to it.Note:Starting v2.3.0, a new templatemfa_base.htmlis introduced, this template is used byMFA.htmlso you can control the styling better and currentmfa_base.htmlextendsbase.htmlSomewhere in your app, add a link to 'mfa_home'<li><a href="{% url 'mfa_home' %}">Security</a> </li>For Example, See 'example' app and look at EXAMPLE.md to see how to set it up.Going PasswordlessTo be able to go passwordless for returning users, create a cookie  named 'base_username' containing username as shown in snippet belowresponse=render(request,'Dashboard.html',context))ifrequest.session.get("mfa",{}).get("verified",False)andgetattr(settings,"MFA_QUICKLOGIN",False):ifrequest.session["mfa"]["method"]!="Trusted Device":response.set_cookie("base_username",request.user.username,path="/",max_age=15*24*60*60)returnresponseSecond, update the GET part of your login viewif"mfa"insettings.INSTALLED_APPSandgetattr(settings,"MFA_QUICKLOGIN",False)andrequest.COOKIES.get('base_username'):username=request.COOKIES.get('base_username')frommfa.helpersimporthas_mfares=has_mfa(username=username,request=request,)ifres:returnres## continue and return the form.Checking MFA on Client SideSometimes you like to verify that the user is still there so simple you can ask django-mfa2 to check that for you{% include 'mfa_check.html' %}functionsuccess_func(){//logic if mfa check succeeds}functionfail_func(){//logic if mfa check fails}functionsome_func(){recheck_mfa(success_func,fail_func,MUST_BE_MFA)//MUST_BE_MFA true or false, if the user must has with MFA}Contributorsmahmoodnasrd3clineswainnunramkwillinghamAndreasDickowmnelson4ezrajriceSpitfireappeterthomassenSecurity contact informationTo report a security vulnerability, please use theTidelift security contact. Tidelift will coordinate the fix and disclosure.