'How to login with mobile/otp using Django Oauth Toolkit
We are using Django OAuth Toolkit with DRF(Django Rest Framework). Now, we want to provide login with mobile number. To authenticate we'll use OTP(One Time Password). How can this be achieved?
- One solution is to directly create auth-token which doesn't look like a wise idea.
Solution 1:[1]
Since this is the top search result for 'OTP with DOT (Django OAuth Toolkit)', answering this to help others.
After going through the DOT tutorials, and creating a provider, please see if the authentication endpoint (/o/token/
) is working with username
and password
, to validate that the setup is successful, you can use it. If you are not able to generate the token using the above approach, please do not proceed further. Please go through the docs properly, or raise separate question.
Now, if you have been able to generate token using username
and password
, create a Validator
by extending oauth2_provider.oauth2_validators.OAuth2Validator
like below. The main idea is to override the validate_user
method of the OAuth2Validator
to get user using your OTP
. A sample implementation is shown below:
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
Now, need to tell DOT about this Validator. Insert following configuration to your settings.py
# Need the provider to extend the functionality to use OTP as login method
OAUTH2_PROVIDER = {
'OAUTH2_VALIDATOR_CLASS': 'MyOAuth2Validator'
}
You can use the /o/token/
endpoints with your custom fields. Only caveat is, that you might have to send the username
and password
fields to bypass the validation test. But you can send some dummy data in those fields.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abhishek |