我们正在使用Django OAuth Toolkit和DRF(Django Rest Framework)。现在,我们希望提供登录手机号码。要进行身份验证,我们将使用OTP(一次性密码)。如何实现这一目标?
答案 0 :(得分:0)
由于这是使用DOT(Django OAuth Toolkit)' OTP的最佳搜索结果,因此请回答此问题以帮助其他人。
完成DOT教程并创建提供程序后,请查看身份验证终结点(/o/token/
)是否与username
和password
一起使用,以验证设置是否成功,你可以使用它。如果您无法使用上述方法生成令牌,请不要继续。请正确浏览文档,或提出单独的问题。
现在,如果您能够使用username
和password
生成令牌,请通过扩展Validator
创建oauth2_provider.oauth2_validators.OAuth2Validator
,如下所示。主要想法是覆盖validate_user
的{{1}}方法,以使用户使用您的OAuth2Validator
。示例实现如下所示:
OTP
现在,需要告诉DOT这个Validator。将以下配置插入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
settings.py
您可以将# Need the provider to extend the functionality to use OTP as login method
OAUTH2_PROVIDER = {
'OAUTH2_VALIDATOR_CLASS': 'MyOAuth2Validator'
}
端点与自定义字段一起使用。唯一需要注意的是,您可能需要发送/o/token/
和username
字段才能绕过验证测试。但是你可以在这些字段中发送一些虚拟数据。