How to implement OTP based Authentication on Django-rest-framework
Security is one of the fields in Computer Science, that is never going to die. As things are getting advanced, security concerns are also increasing day by day.
So, you might be concerned with it, and might want to have some kind of security Authentication in your project.
There are different kinds of authentication techniques:
- Password authentication
- Two-factor authentication (2FA)
- Token authentication
- Biometric authentication
etc….
Reference: https://www.solarwindsmsp.com/blog/network-authentication-methods
Through OTP functionality we can implement 2FA in our projects.
So why do we need 2FA?
In password authentication, we require a password to get authorised for accessing the restricted content. As it is a direct way and if a hacker by any means gets into the server through login, then your data may get stolen effortlessly. For this we can have an intermediate step, We can authenticate the user if and only if One Time Password is correct. One-time password can be sent through any means, such as email, Mobile etc.
Let’s learn by doing.
How OTP Works?
The flow chart depicts the flow of the process.
- At first, the OTP code is requested by the client, through a provided phone number or email.
- Then a Key is Generated valid for that particular instance.
- OTP is created and sent to the client through the provided medium.
- The user enters the OTP code on the portal provided by us.
- Afterwards, The OTP is validated by the server.
How to implement it in Django?
We can implement the 2FA through OTP using a python package/library called PyOTP.
PyOTP provides all the functionality for OTP creation and validation.
Base64 will be used for key generation.
In PyOTP we have to types of use cases:
- Time-Based OTPs
- Counter-Based OTPs
Reference: https://pypi.org/project/pyotp/
Both ways are good but for now, we will use Counter-Based OTPs. In counter-based OTP a new 6 digit code is generated on every new counter number.
hotp = pyotp.HOTP('base32secret3232')
hotp.at(0) # => '260182'
hotp.at(1) # => '055283'
hotp.at(1401) # => '316439'
Whole project Reference: https://github.com/Akash16s/OTP-in-django
You can refer to the above-provided link of a GitHub repo as I will not teach you about Django rest framework in this tutorial.
To learn Django-rest Framework in minutes: https://www.youtube.com/watch?v=ejJ-2oz4AgI
File Structure
OTP
├── --init__.py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
verification
├── --init__.py
├── admin.py
├── apps.py
├── migrations
├── models.py
├── tests.py
├── urls.py
└── views.py
--manage.py
Let’s start by having an application named Verification.
The project is configured in the following manner.
GET
This is to register the mobile number into the database and generate OTP.
http://127.0.0.1:8000/verify/<phone>/
POST
This is to verify the mobile number using OTP.
http://127.0.0.1:8000/verify/<phone>/
JSON Data:
{
"otp":040301
}
We want to store the data for every new signup. So we have the following model in our Django Model.
Models:
class phoneModel(models.Model):
Mobile = models.IntegerField(blank=False)
isVerified = models.BooleanField(blank=False, default=False)
counter = models.IntegerField(default=0, blank=False)def __str__(self):
return str(self.Mobile)
Now as you are ready with the skeleton of the server we can now proceed to writing down the code for the OTP.
While designing the OTP functionality we have to make sure that the above-provided Flow Diagram should satisfy.
The Get Request:
We will not go into the networking side of what gets do instead we’ll just use it as an API to communicate with the server. The user requests for the OTP through this particular GET request.
Step 1: Add the data in the database if it doesn’t exist and create a particular Model’s Object of the user. Update the counter as well.
Step 2: Generate a key of base32 using base64 library.
Step 3: Use the Key to generate an Object of the class pyotp.
Step 4: Now using the Counter of User model and pyotp object generate the OTP code.
Step 5: Using mailing or messaging service send the OTP code to the user.
The Post Request
We will not go into the networking side of what post request does but we’ll just use it as an API to communicate with the server. The user tries to validate the OTP using a POST request.
Step 1: Find that phone number existing in the phone model.
Step 2: Generate a key of base32 using base64 library.
Step 3: Use the Key to generate an Object of class pyotp.
Step 4: Now using the Counter of User model and OTP code sent by the user, validate the authenticity of the user.
Step 6: Now send the user Authorization token for further authorization.
Here’s the code
Hence you have implemented the OTP functionality in your Django-rest-framework project.
Congratulations on completing the code.
I hope this tutorial will help you a lot in your future projects. Share this article with your colleagues and friends.
Complete code: https://github.com/Akash16s/OTP-in-django
Thanks for being here with me till the end. I am currently in the starting days of writing articles so, please comment below about the article, your comments mean a lot to me.
You can follow me on Twitter, GitHub, Medium, LinkedIn.
Don’t forget to follow Camping with python.
If you have any doubts regarding this tutorial or have any other issue or you want to suggest something, you can comment below.
The next article will be up soon until then keep practising.