如何使用 Django Oauth Toolkit 使用 mobile/otp 登录

Kum*_*tin 2 python django-rest-framework django-rest-auth django-oauth

我们正在使用带有 DRF(Django Rest Framework)的 Django OAuth 工具包。现在,我们要提供手机号码登录。为了进行身份验证,我们将使用 OTP(一次性密码)。如何做到这一点?

  • 一种解决方案是直接创建 auth-token,这看起来不是一个明智的想法。

Abh*_*hek 7

由于这是“带有 DOT 的 OTP(Django OAuth 工具包)”的最佳搜索结果,因此回答此问题以帮助其他人。

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

现在,如果您已经能够使用usernameand生成令牌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
Run Code Online (Sandbox Code Playgroud)

现在,需要告诉 DOT 关于这个验证器。将以下配置插入到您的settings.py

# Need the provider to extend the functionality to use OTP as login method
OAUTH2_PROVIDER = {
    'OAUTH2_VALIDATOR_CLASS': 'MyOAuth2Validator'
}
Run Code Online (Sandbox Code Playgroud)

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