如何使用Django Oauth Toolkit

时间:2016-06-07 12:13:06

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

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

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

1 个答案:

答案 0 :(得分:0)

由于这是使用DOT(Django OAuth Toolkit)' OTP的最佳搜索结果,因此请回答此问题以帮助其他人。

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

现在,如果您能够使用usernamepassword生成令牌,请通过扩展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字段才能绕过验证测试。但是你可以在这些字段中发送一些虚拟数据。