最近刚好看到这个模块,简单实验了下,具体操作如下:
模块地址: https://github.com/Alireza2n/django-multifactor
环境:
Python 3.9.6
Django==4.1.2
需要安装如下2个包:
django-multifactor==0.8.3
django-decorator-include==3.3
修改 settings.py 增加如下内容
INSTALLED_APPS = [
.... 默认的设置 ....
"multifactor",
]
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
# 双因素
MULTIFACTOR = {
'FACTORS': ['FIDO2', 'U2F', 'TOTP'], # <- this is the default
'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': True, # {OPTIONAL} <bool> Set to False to not create a post-login message
}
在项目的最高层级的 urls.py 添加如下内容
from decorator_include import decorator_include
from multifactor.decorators import multifactor_protected
urlpatterns = [
path('admin/multifactor/', include('multifactor.urls')),
# 修改admin登陆地址
path('admin/', decorator_include(multifactor_protected(factors=1), admin.site.urls)),
... 这里是之前的配置 ...
]
迁移表结构
python manage.py migrate
执行完后,数据库会多2个表
会在数据库生成2张表
> show tables like '%multifactor%';
+--------------------------------+
| Tables_in_mxdb (%multifactor%) |
+--------------------------------+
| multifactor_disabledfallback |
| multifactor_userkey |
+--------------------------------+
2 rows in set (0.01 sec)
前台启动
python manage.py runserver 0.0.0.0:8118
然后登录admin后台,输入账号密码后,会自动跳转到 totp绑定页面
手机扫码绑定后,后续再次登录就需要输入验证码了。
数据库里面的记录如下:
[dba_platform] > select * from multifactor_userkey \G
*************************** 1. row ***************************
id: 1
properties: {"secret_key": "RF4KSD5G4ZXXXXXXXX4DCQ4I"}
key_type: TOTP
enabled: 1
added_on: 2025-08-07 14:03:49.681141
expires: NULL
last_used: 2025-08-07 15:06:41.488010
user_id: 5
name: NULL
不足之处:
这个启用关闭MFA的操作是全局的配置,启用后全部账号都需要配置mfa,对于直接通过接口访问的操作就无法执行了。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。