Wouldn’t it be great to get OTP on mobile instead of in response? Well its interesting to me. Lets see how to implement that logic using the code from the previous topic (2 factor auth).

TWILIO INTEGRATION

First we need to create a trail account in twilio and buy a number from which we will be sending the messages.

twilio account
twilio number

Lets add Twilio dependency first to our spring application we created in the previous project.

Now lets register our application with twilio. For that we need Account SID, Auth Token. Let store it in a constants class.

You can get the SID and Token from Account info page of your twilio account:

Lets initilize Twilio in our application with SID and Token

Now that all is initlized and setup, lets generate logic. We will have to add a new class CustomUserDetails which will implement UserDetailsClass so that we will have UserData in it and get the phoneNumber from it.

Now lets use this CustomUserDetails in our UserDetialsService logic to send CustomUserDetails object which will contain all user data from DB.

Logic to generate OTP and send to mobile number:

Here we are getting CustomUserDetails from UserDetailsService. generateOtp() will accept 2 arguments username and mobilenumber. The logic will be to create random 6 digit and send to the mobile number as well as store in the DB for validation. Evertime the user enters OTP the otp in request will be matched with the OTP in DB.

Message.creator() method is the one provided by TWILIO. It accepts 3 parameters mobile no to send the message to, mobile no from which the message will be sent and the message that needs to be sent.

Lets test this code now. Send username and password first. A new OTP should be generated and sent to mobile number as well as in the response.

Validate OTP :

Leave a Reply

Your email address will not be published. Required fields are marked *