Thursday, August 21, 2014

Mobile Application - SMS Verification

Registration verification is becoming mandatory to keep the end user confidence, user identity and security. Verification process either follows the Email / SMS approach. Emails verifications traditionally has flaw of user identity validation and leads to spamming such verifications are suitable only for the web based interface and web interface needs be backed up with proper security layers to keep customer away from the spam / malware / etc. attacks. 

Mobile application has different set of challenges for validate the customer identity, with guidelines "not all the mobile users will have email accounts", SMS short code verification is industry followed approach to validate the user identity. Leading applications uses this process to authenticate the user registration.  

Email verification won’t add much OPEX for the user authentication use case but SMS verification adds cost to the OPEX, but covers all kind of mobile users across the glob. Keeping user identify will provide flexibility for migrating the users from one device to another device. SMS verification authenticates the user device and help to stop /block all security related attacks.  

Many companies provides cloud based SMS / Voice calls options which help to reach-out the end users across the geographical location in a quicker and easier ways. Pricing and way to send the messages changes been the cloud service providers. Twilio, Nexmo & BulkSms solutions are currently used by the major mobile applications to authenticate the user mobile device.




Twillio 



Twillio provides voice and messaging to the web and mobile applications. Twillio is powerful / low cost of entry / extremely simple interface. 

Typical Cost Plan 

 United Kingdom    0.04$      Per Send
 India                   0.01$      Per Send
 US                     0.0075$   Per Send
 Singapore             0.012$    Per Send
 France                0.07$     Per Send
 Spain                  0.08$     Per Send
 Italy                    0.072$   Per Send


Assumption :
 - 10000k / month subscription from US :         75.00$
 - 10000k / month subscription from UK :        400.00$
 - 10000k / month subscription from India :     100.00$
 - 10000k / month subscription from Singapore : 120.00$
 - 10000k / month subscription from France :    700.00$

                                               = 1395.00 $ / month / 50K subscription

Using Twillio with REST DropWizard framework 


Step 1: Register for account in the Twillio



Need to provide valid mobile number for registration and need to provide the verification code for authentication. Twillio provides option to simulate the voice and sms calls and provides API calls which used to invoke the sample calls. Store the unique phone number generated for your account, that number will be used for all communication as FROM / Originator of the SMS messages. 

Step 2: Get Authentication Id and Token from the account dashboard



Step 3: Include latest Twillio SDK library in the Maven XML

<dependency>
    <groupId>com.twilio.sdk</groupId>
    <artifactId>twilio-java-sdk</artifactId>
    <version>3.4.5</version>
</dependency>

Step 4: Create Dropwizard Configuration with Twillio Authentication Details. 

....
twilioConfiguration:
  accountId:  < account ID received from the Twillio page >
  accountToken: < account token received from the Twillio account page >


  number: < unique number generated for the Twillio account >
....

Step 5: Twillio Dropwizard Configuration Loader.

import com.fasterxml.jackson.annotation.JsonProperty;

public class TwilioConfiguration {

       public String getAccountId() {
             return accountId;
       }

       public void setAccountId(String accountId) {
             this.accountId = accountId;
       }

       public String getAccountToken() {
             return accountToken;
       }

       public void setAccountToken(String accountToken) {
             this.accountToken = accountToken;
       }

       public String getNumber() {
             return number;
       }

       public void setNumber(String number) {
             this.number = number;
       }

       @NotEmpty
       @JsonProperty
       private String accountId;

       @NotEmpty
       @JsonProperty
       private String accountToken;

       @NotEmpty
       @JsonProperty
       private String number;

}


Step 6: Include the configuration in the master application configuration.

            ......
       @Valid
       @NotNull
       @JsonProperty
       private TwilioConfiguration twilioConfiguration;
      
       public TwilioConfiguration getTwilioConfiguration() {
             return twilioConfiguration;
       }

public void setTwilioConfiguration(TwilioConfiguration twilioConfiguration) {
             this.twilioConfiguration = twilioConfiguration;

       }
       ......

Step 7: Create a class which can use Twillio SDK to send SMS.

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;

public class TwilioVerificationSmsSender {

       private final String accountId;
      
       private final String accountToken;
      
       private final String number;


       public TwilioVerificationSmsSender (TwilioConfiguration config) {
            
             this.accountId = config.getAccountId();
            
             this.accountToken = config.getAccountToken();
            
             this.number = config.getNumber();
       }

       public void sendSmsVerificationCode(String destination,
                    String verificationCode) throws IOException, TwilioRestException {
      
             TwilioRestClient client = new TwilioRestClient(accountId, accountToken);
            
             MessageFactory messageFactory = client.getAccount().getMessageFactory();
            
             List messageParameters = new LinkedList<>();
            
             messageParameters.add(new BasicNameValuePair("To", destination));
            
             messageParameters.add(new BasicNameValuePair("From", number));
            
             messageParameters.add(new BasicNameValuePair("Body", "Authentication code for accessing the application:" + verificationCode));

             try {
                   
                    messageFactory.create(messageParameters);
                   
             } catch (RuntimeException damnYouTwilio) {
                    throw new IOException(damnYouTwilio);
             }
       }


Step 8: Create a Dropwizard controller to handle the registration. 
In the controller REST API for registration will help to communicate the short code to the destination.

          .....
       @Timed
       @GET
       @Path("/sms/code/{number}")
       public Response createAccount(@PathParam("number") String number) {

             // Check the validity of the destination number
             //
             if (!Utility.isValidPhoneNumber(number)) {

                    logger.error("Invalid destination number [ " + number + " ]");

                    throw new MobileApplicationException(Response.status(400).build());
             }

             VerificationCode verificationCode = generateUniqueVerificationCode();

            
             try {
                    twillioSender.sendSmsVerificationCode
                           (number, generateUniqueVerificationCode ());

             } catch (IOException e) {
                    e.printStackTrace();
             }
            
             return Response.ok().build();

       }

protected int generateUniqueVerificationCode () {
             try {
                    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

                    int code = 100000 + random.nextInt(900000);

                    return new code;

             } catch (NoSuchAlgorithmException e) {
                    throw new AssertionError(e);
             }
       }
       .....


Will cover the Nexom and BulkSms solution usage in next article.

No comments: