Register by 10/16 for $250 off the on-site price.

Twilio Verify Phone Verification Java/Spring Quickstart

Phone Verification is an important, high-confidence step in a registration flow to verify that a user has the device they claim to have. Adding Twilio Verify phone verification to your application will greatly reduce your number of fraudulent registrations and protect future application users from having their numbers registered by scammers.

This quickstart guides you through creating a JavaSpring and AngularJS app that requires a phone verification step to create an account. Two channels of phone verification are demoed: SMS and Voice.

Ready to add Twilio Verify to a demo app and keep the bad actors away? Enter stage left!

Sign Into (or Create) a Twilio Account

Either sign up for a free Twilio trial, or sign into an existing Twilio account.

Create a New Authy Application

Once logged in, visit the Authy Console. Click on the red 'Create New Aplication' (or big red plus ('+') if you already created one) to create a new Authy application then name it something memorable.

Authy create new application

Twilio will redirect you to the Settings page next:

Account Security API Key

Click the eyeball icon to reveal your Production API Key, and copy it somewhere safe. You will use the API Key during the application setup step below.

Clone and Setup the Application

Start by cloning our Spring repository. Enter the directory and use npm to install all of our dependencies:

gradle build
  1. Open the file .env.example
  2. Change ACCOUNT_SECURITY_API_KEY to the API Key from the above step
  3. Now, save the file as .env
  4. Source or otherwise set the environment variable in your environment
Loading Code Samples...
Language
# You can get/create one here :
# https://www.twilio.com/console/authy/applications
ACCOUNT_SECURITY_API_KEY='ENTER_SECRET_HERE'
Enter the API Key from the Authy console and optionally change the port.
Enter an Application API Key

Enter the API Key from the Authy console and optionally change the port.

And that's all the setup you'll need!

Now, launch the application with:

gradle appRun

Assuming your API Key is correctly entered you'll soon get a message that the app is up!

Use the Java-Spring Verify Phone Verification Demo

Keeping your phone at your side, vist the phone verification page of the demo at http://localhost:8080/verification/

Enter a Country Code and Phone Number, then choose which channel to request verification over, 'SMS' or 'CALL' (Voice). Finally, hit the blue 'Request Verification' button and wait.

Phone Verification by SMS or Voice

You won't be waiting long - you'll either receive a phone call or an SMS with the verification token. If you requested a phone call, as an additional security feature you may need to interact to proceed (by entering a number on the phone keypad).

Loading Code Samples...
Language
package com.twilio.accountsecurity.services;

import com.authy.AuthyApiClient;
import com.authy.api.Params;
import com.authy.api.Verification;
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PhoneVerificationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);

    private AuthyApiClient authyApiClient;

    @Autowired
    public PhoneVerificationService(AuthyApiClient authyApiClient) {
        this.authyApiClient = authyApiClient;
    }

    public void start(String countryCode, String phoneNumber, String via) {
        Params params = new Params();
        params.setAttribute("code_length", "4");
        Verification verification = authyApiClient
                .getPhoneVerification()
                .start(phoneNumber, countryCode, via, params);

        if(!verification.isOk()) {
            logAndThrow("Error requesting phone verification. " +
                    verification.getMessage());
        }
    }

    public void verify(String countryCode, String phoneNumber, String token) {
        Verification verification = authyApiClient
                .getPhoneVerification()
                .check(phoneNumber, countryCode, token);

        if(!verification.isOk()) {
            logAndThrow("Error verifying token. " + verification.getMessage());
        }
    }

    private void logAndThrow(String message) {
        LOGGER.warn(message);
        throw new TokenVerificationException(message);
    }
}
This function allows you to send the verification code over SMS or Voice depending on the 'via' variable.
Send a Phone Verification via SMS or Voice

This function allows you to send the verification code over SMS or Voice depending on the 'via' variable.

Either way you requested the passcode, enter the token into the Verification entry form and click 'Verify Phone':

Phone Verification Entry Box

Loading Code Samples...
Language
package com.twilio.accountsecurity.services;

import com.authy.AuthyApiClient;
import com.authy.api.Params;
import com.authy.api.Verification;
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PhoneVerificationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);

    private AuthyApiClient authyApiClient;

    @Autowired
    public PhoneVerificationService(AuthyApiClient authyApiClient) {
        this.authyApiClient = authyApiClient;
    }

    public void start(String countryCode, String phoneNumber, String via) {
        Params params = new Params();
        params.setAttribute("code_length", "4");
        Verification verification = authyApiClient
                .getPhoneVerification()
                .start(phoneNumber, countryCode, via, params);

        if(!verification.isOk()) {
            logAndThrow("Error requesting phone verification. " +
                    verification.getMessage());
        }
    }

    public void verify(String countryCode, String phoneNumber, String token) {
        Verification verification = authyApiClient
                .getPhoneVerification()
                .check(phoneNumber, countryCode, token);

        if(!verification.isOk()) {
            logAndThrow("Error verifying token. " + verification.getMessage());
        }
    }

    private void logAndThrow(String message) {
        LOGGER.warn(message);
        throw new TokenVerificationException(message);
    }
}
This function verifies the token delivered over the Voice or SMS channel.
Verify a Token

This function verifies the token delivered over the Voice or SMS channel.

And with that, your demo app is protected with Twilio's Verify! You can now log out to try the other channel.

What's Next?

Your demo app is now keeping hordes of fraudulent users from registering with your business and polluting the database. Next, check out all of the variables and options available to you in the Verify API Reference. Also, for protecting your customers in an ongoing manner (with this same codebase) try the Java Spring Authy Two-Factor Authentication Quickstart.

After that, take a stroll through the Docs for more Account Security demos and tutorials - as well as sample web applications using all of Twilio's products.

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Samples...
# You can get/create one here :
# https://www.twilio.com/console/authy/applications
ACCOUNT_SECURITY_API_KEY='ENTER_SECRET_HERE'
package com.twilio.accountsecurity.services;

import com.authy.AuthyApiClient;
import com.authy.api.Params;
import com.authy.api.Verification;
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PhoneVerificationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);

    private AuthyApiClient authyApiClient;

    @Autowired
    public PhoneVerificationService(AuthyApiClient authyApiClient) {
        this.authyApiClient = authyApiClient;
    }

    public void start(String countryCode, String phoneNumber, String via) {
        Params params = new Params();
        params.setAttribute("code_length", "4");
        Verification verification = authyApiClient
                .getPhoneVerification()
                .start(phoneNumber, countryCode, via, params);

        if(!verification.isOk()) {
            logAndThrow("Error requesting phone verification. " +
                    verification.getMessage());
        }
    }

    public void verify(String countryCode, String phoneNumber, String token) {
        Verification verification = authyApiClient
                .getPhoneVerification()
                .check(phoneNumber, countryCode, token);

        if(!verification.isOk()) {
            logAndThrow("Error verifying token. " + verification.getMessage());
        }
    }

    private void logAndThrow(String message) {
        LOGGER.warn(message);
        throw new TokenVerificationException(message);
    }
}
package com.twilio.accountsecurity.services;

import com.authy.AuthyApiClient;
import com.authy.api.Params;
import com.authy.api.Verification;
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PhoneVerificationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);

    private AuthyApiClient authyApiClient;

    @Autowired
    public PhoneVerificationService(AuthyApiClient authyApiClient) {
        this.authyApiClient = authyApiClient;
    }

    public void start(String countryCode, String phoneNumber, String via) {
        Params params = new Params();
        params.setAttribute("code_length", "4");
        Verification verification = authyApiClient
                .getPhoneVerification()
                .start(phoneNumber, countryCode, via, params);

        if(!verification.isOk()) {
            logAndThrow("Error requesting phone verification. " +
                    verification.getMessage());
        }
    }

    public void verify(String countryCode, String phoneNumber, String token) {
        Verification verification = authyApiClient
                .getPhoneVerification()
                .check(phoneNumber, countryCode, token);

        if(!verification.isOk()) {
            logAndThrow("Error verifying token. " + verification.getMessage());
        }
    }

    private void logAndThrow(String message) {
        LOGGER.warn(message);
        throw new TokenVerificationException(message);
    }
}