django rest框架jwt 2fa
drf-jwt-2fa的Python项目详细描述
这个包为django rest提供了一个双重身份验证 使用json web令牌的框架。实现基于另一个 称为REST framework JWT Auth的drf身份验证库。
概述
认证流使用两个jwt令牌和一个验证代码:
- 首先,通过提供用户名和 密码。如果用户名和密码正确,则 (7位)验证码生成并通过电子邮件发送到 用户的电子邮件地址。此验证代码与 django的密码散列器和散列包含在代码令牌中。
- 在收到验证码之后,第二个令牌称为 可以请求身份验证令牌。请求由 将代码令牌和验证代码发送到另一个端点。 如果令牌和代码正确,则验证令牌是 返回。此身份验证令牌可用于对 遵循API请求。它与jwt令牌的格式相同 关于REST framework JWT Auth。
要求
- python 2.7、3.4、3.5或3.6
- django 1.11或2.0
- django rest框架
安装
使用以下命令从pypi安装包:
pip install drf-jwt-2fa
配置
配置django rest框架以使用提供的身份验证类 通过在设置中添加类似的内容:
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'drf_jwt_2fa.authentication.Jwt2faAuthentication', ] 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], }
注意:身份验证令牌选项可以配置为 JWT_AUTH配置项,如REST framework JWT Auth中所述。
身份验证api端点的url可以配置为 类似于url.py中的内容::
import drf_jwt_2fa.urls from django.conf.urls import include, url urlpatterns = [ url(r'^auth/', include(drf_jwt_2fa.urls, namespace='auth')), ]
或者单独配置每个视图:
from django.conf.urls import include, url from drf_jwt_2fa.views import obtain_auth_token, obtain_code_token urlpatterns = [ url(r'^get-code-token/', obtain_code_token), url(r'^get-auth-token/', obtain_auth_token), ]
附加设置
有一些附加设置可以覆盖。这些都是 可用设置及其默认值:
JWT2FA_AUTH = { # Length of the verification code (digits) 'CODE_LENGTH': 7, # Characters used in the verification code 'CODE_CHARACTERS': '0123456789', # Secret key to use for signing the Code Tokens 'CODE_TOKEN_SECRET_KEY': hash_string('2fa-code-' + settings.SECRET_KEY), # Secret string to extend the verification code with 'CODE_EXTENSION_SECRET': hash_string('2fa-ext-' + settings.SECRET_KEY), # How long the code token is valid 'CODE_EXPIRATION_TIME': datetime.timedelta(minutes=5), # Throttle limit for code token requests from same IP 'CODE_TOKEN_THROTTLE_RATE': '12/3h', # How much time must pass between verification attempts, i.e. to # request authentication token with a with the same code token and a # verification code 'AUTH_TOKEN_RETRY_WAIT_TIME': datetime.timedelta(seconds=2), # Function that sends the verification code to the user 'CODE_SENDER': 'drf_jwt_2fa.sending.send_verification_code_via_email', # From Address used by the e-mail sender 'EMAIL_SENDER_FROM_ADDRESS': settings.DEFAULT_FROM_EMAIL, # Set to this to a (translated) string to override the default # message subject of the e-mail sender 'EMAIL_SENDER_SUBJECT_OVERRIDE': None, # Set to this to a (translated) string to override the default # message body of the e-mail sender 'EMAIL_SENDER_BODY_OVERRIDE': None, }