如何在Django中实现两步验证(2FA)
- 安装Django Two-Factor Authentication
在Django中实现两步验证最简单的方式就是使用第三方库,这里我们选择Django Two-Factor Authentication。首先使用pip安装:
pip install django-two-factor-auth
- 配置settings.py
在Django项目的settings.py中进行如下配置:
INSTALLED_APPS = [ # ... 'django_otp', 'django_otp.plugins.otp_totp', 'two_factor', ] MIDDLEWARE = [ # ... 'two_factor.middleware.threadlocals.ThreadLocals', 'two_factor.middleware.csrf.CookieXsrfTokenMiddleware', 'two_factor.middleware.authy.AdminRequiredMiddleware', 'two_factor.middleware.phone_required.PhoneRequiredMiddleware', ] LOGIN_URL = 'two_factor:login' LOGIN_REDIRECT_URL = 'two_factor:profile' LOGIN_EXEMPT_URLS = ( r'^accounts/login/$', r'^accounts/logout/$', r'^accounts/signup/$', r'^accounts/password/change/$', r'^accounts/password/reset/$', r'^accounts/confirm-email/$', ) AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'two_factor.auth_backends.OTPAuthenticationBackend', ] TWO_FACTOR_SMS_GATEWAY = 'two_factor.gateways.twilio.gateway.TwilioGateway' TWO_FACTOR_PHONE_MODEL = 'two_factor.phonemodels.Phone' TWO_FACTOR_PATCH_ADMIN = True # 调整消息框的位置 from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.ERROR: 'danger', }
- 数据库迁移
在settings.py中配置好之后需要进行数据库迁移:
python manage.py makemigrations python manage.py migrate
- 创建superuser
在进行两步验证之前需要创建一个superuser:
python manage.py createsuperuser
- 配置警告信息
由于两步验证需要安装设备,需要提醒用户进行设置。在Django Two-Factor Authentication中提供了两种方式来提醒用户:消息和警告消息,警告消息会出现在每个页面的顶部。下面是配置示例(在模板文件中定义):
{% extends 'two_factor/base.html' %} {% block title %}Profile{% endblock %} {% block content %} {% if profile.nogadget_warning %} <div class="alert alert-warning"> {% trans "You have not configured any Devices for use with Two-Factor Authentication." %} <a href="{% url 'two_factor:setup' %}">{% trans "Setup Two-Factor Authentication" %}</a> </div> {% endif %} {% if profile.gadget_warning %} <div class="alert alert-warning"> {% trans "You need to configure more Devices for use with Two-Factor Authentication." %} <a href="{% url 'two_factor:setup' %}">{% trans "Setup Two-Factor Authentication" %}</a> </div> {% endif %} {% if profile.totp_set %} <div class="card-body"> <h4 class="card-title">{% trans "Google Authenticator" %}</h4> <p class="card-text">{% trans "Scan the QR code below with Google Authenticator to set up Two-Factor Authentication." %}</p> <img src="{{ profile.qrcode }}" alt="qrcode"> <p class="card-text">{% trans "If you are unable to scan the QR code, copy and paste the code below into Google Authenticator." %}</p> <pre>{{ profile.totp }}</pre> </div> {% endif %} {% endblock %}
- 设置两步验证
在浏览器中输入http://localhost:8000/accounts/login/,进入登录页面。这时系统会提示你输入用户名和密码,输入系统管理员的用户名和密码后系统会提示你配置两步验证,按照提示进行配置即可。
至此,Django中的两步验证就已经配置完成了,可以在用户登录时进行验证。
相关文章