我们将 Django OAuth Toolkit 与 DRF(Django Rest Framework)一起使用。现在,我们要提供手机号码登录。为了进行身份验证,我们将使用 OTP(一次性密码)。如何做到这一点?
- 一种解决方案是直接创建 auth-token,这看起来并不明智。
我们将 Django OAuth Toolkit 与 DRF(Django Rest Framework)一起使用。现在,我们要提供手机号码登录。为了进行身份验证,我们将使用 OTP(一次性密码)。如何做到这一点?
由于这是 'OTP with DOT (Django OAuth Toolkit)' 的热门搜索结果,因此回答此问题以帮助其他人。
完成 DOT 教程并创建提供程序后,请查看身份验证端点 ( /o/token/
) 是否正在使用,username
并且password
要验证设置是否成功,您可以使用它。如果您无法使用上述方法生成令牌,请不要继续进行。请正确浏览文档,或提出单独的问题。
现在,如果您已经能够使用username
and生成令牌,请通过如下扩展来password
创建一个。主要思想是覆盖让用户使用您的. 示例实现如下所示:Validator
oauth2_provider.oauth2_validators.OAuth2Validator
validate_user
OAuth2Validator
OTP
from oauth2_provider.oauth2_validators import OAuth2Validator
from django.contrib.auth import get_user_model
USER_MODEL = get_user_model()
class MyOAuth2Validator(OAuth2Validator): # pylint: disable=w0223
""" Primarily extend the functionality of token generation """
def validate_user(self, username, password, client, request, *args, **kwargs):
""" Here, you would be able to access the MOBILE/ OTP fields
which you will be sending in the request.post body. """
# otp = request.otp
# mobile = request.mobile
# user = AppropriateModel.objects.get(otp=otp, mobile=mobile)
user = USER_MODEL.objects.get(id=1)
if user is not None and user.is_active:
request.user = user
return True
return False
现在,需要告诉 DOT 这个 Validator。将以下配置插入到您的settings.py
# Need the provider to extend the functionality to use OTP as login method
OAUTH2_PROVIDER = {
'OAUTH2_VALIDATOR_CLASS': 'MyOAuth2Validator'
}
您可以将/o/token/
端点与您的自定义字段一起使用。唯一需要注意的是,您可能必须发送username
andpassword
字段才能绕过验证测试。但是您可以在这些字段中发送一些虚拟数据。