gpt4 book ai didi

python - 如何使用 Django Oauth Toolkit 通过 mobile/otp 登录

转载 作者:行者123 更新时间:2023-12-01 03:54:39 24 4
gpt4 key购买 nike

我们正在使用 Django OAuth Toolkit 和 DRF(Django Rest Framework)。现在,我们要提供手机号码登录。为了进行身份验证,我们将使用 OTP(一次性密码)。如何实现这一目标?

  • 一种解决方案是直接创建身份验证 token ,这看起来不是一个明智的主意。

最佳答案

由于这是“OTP with DOT (Django OAuth Toolkit)”的热门搜索结果,因此回答此问题以帮助其他人。

完成 DOT 教程并创建提供程序后,请查看身份验证端点 (/o/token/) 是否与 username 配合使用密码,验证设置成功,可以使用。如果您无法使用上述方法生成 token ,请不要继续操作。请正确阅读文档,或提出单独的问题。

现在,如果您能够使用用户名密码生成 token ,请通过扩展oauth2_provider.oauth2_validators创建一个Validator .OAuth2Validator 如下所示。主要思想是重写 OAuth2Validatorvalidate_user 方法,让用户使用您的 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 有关此验证器的信息。将以下配置插入到您的 settings.py

# Need the provider to extend the functionality to use OTP as login method
OAUTH2_PROVIDER = {
'OAUTH2_VALIDATOR_CLASS': 'MyOAuth2Validator'
}

您可以将 /o/token/ 端点与自定义字段结合使用。唯一需要注意的是,您可能必须发送用户名密码字段才能绕过验证测试。但您可以在这些字段中发送一些虚拟数据。

关于python - 如何使用 Django Oauth Toolkit 通过 mobile/otp 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37679067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com