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

标签 python django-rest-framework django-rest-auth django-oauth

我们正在使用 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/

相关文章:

django - 如何限制表单页面中的外键选择?

django - django Rest auth 和 React Native 的问题

djangorest框架csrf token 丢失或不正确

reactjs - Django, Djoser 社交身份验证 : State could not be found in server-side session data. status_code 400

python - 类变量对于不同的实例具有不同的值

python - NET::ERR_CERT_COMMON_NAME_INVALID - 错误消息

python - 使用 Django Rest Framework 将操作字段添加到帖子中

Django REST Framework - 405 METHOD NOT ALLOWED using SimpleRouter

python - 用于密码重置的 Django-rest-auth HTML 电子邮件

python - Sublime Text : How to get the file name of the current view