Java (Spring) Quickstart for Twilio Authy - Twilio
Register for SIGNAL by 8/31 for $250 off. Register now.

Java-Spring Quickstart for Twilio Authy Two-factor Authentication

Adding Two-factor Authentication to your application is the easiest way to increase security and trust in your product without unnecessarily burdening your users. This quickstart guides you through building a Java, Spring and AngularJS application that restricts access to a URL. Four Authy API channels are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect a tiny app from big hacking efforts?

Sign Into (or Sign Up For) a Twilio Account

Create a new Twilio account (you can 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

You'll automatically be transported to the Settings page next. Click the eyeball icon to reveal your Production API Key.

Account Security API Key

Copy your Production API Key to a safe place, you will use it during application setup.

Set up the Authy Client on Your Device

This Two-factor Authentication demos two channels which require an installed Authy Client to test: Soft Tokens and Push Notifications. While SMS and Voice channels will work without the client, to try out all four authentication channels download and install Authy Client for Desktop or Mobile:

Clone and Setup the Application

Clone our Java repository locally, then enter the directory. Install all of the necessary node modules:

gradle build

Next, open the file .env.example. There, edit the ACCOUNT_SECURITY_API_KEY, pasting in the API Key from the above step (in the console), and save the file as .env. Either source the .env file or otherwise set the ACCOUNT_SECURITY_API_KEY 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 Account Security console and optionally change the port.
Add Your Application API Key

Enter the API Key from the Account Security console and optionally change the port.

 Once you have added your API Key, you are ready to run! Launch the app with:

gradle appRun

You should get a message your new app is running!

Try the Java Spring Authy Two-Factor Demo

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to http://localhost:8080/register/index.html

Enter your information and invent a password, then hit 'Register'. Your information is passed to Twilio (you will be able to see your user immediately in the console), and the application is returned a user_id.

Now visit http://localhost:8080/login/index.html and login. You'll be presented with a happy screen:

Token Verification Page

 

If your phone has the Authy Client installed, you can immediately enter a Soft Token from the client to Verify. Additionally, you can try a Push Notification simply by pushing the labeled button.

If you do not have the Authy Client installed, the SMS and Voice channels will also work in providing a token. To try different channels, you can logout to start the process again.

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

import com.authy.AuthyApiClient;
import com.authy.OneTouchException;
import com.authy.api.*;
import com.twilio.accountsecurity.controllers.requests.VerifyTokenRequest;
import com.twilio.accountsecurity.repositories.UserRepository;
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
import com.twilio.accountsecurity.models.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenService {

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

    private AuthyApiClient authyClient;
    private UserRepository userRepository;

    @Autowired
    public TokenService(AuthyApiClient authyClient, UserRepository userRepository) {
        this.authyClient = authyClient;
        this.userRepository = userRepository;
    }


    public void sendSmsToken(String username) {
        Hash hash = authyClient
                .getUsers()
                .requestSms(getUserAuthyId(username));

        if(!hash.isOk()) {
            logAndThrow("Problem sending token over SMS. " + hash.getMessage());
        }
    }

    public void sendVoiceToken(String username) {
        UserModel user = userRepository.findFirstByUsername(username);

        Hash hash = authyClient.getUsers().requestCall(user.getAuthyId());
        if(!hash.isOk()) {
            logAndThrow("Problem sending the token on a call. " + hash.getMessage());
        }
    }

    public String sendOneTouchToken(String username) {
        UserModel user = userRepository.findFirstByUsername(username);

        try {
            ApprovalRequestParams params = new ApprovalRequestParams
                    .Builder(user.getAuthyId(), "Login requested for Account Security account.")
                    .setSecondsToExpire(120L)
                    .addDetail("Authy ID", user.getAuthyId().toString())
                    .addDetail("Username", user.getUsername())
                    .addDetail("Location", "San Francisco, CA")
                    .addDetail("Reason", "Demo by Account Security")
                    .build();
            OneTouchResponse response = authyClient
                    .getOneTouch()
                    .sendApprovalRequest(params);

            if(!response.isSuccess()) {
                logAndThrow("Problem sending the token with OneTouch");
            }
            return response.getApprovalRequest().getUUID();
        } catch (OneTouchException e) {
            logAndThrow("Problem sending the token with OneTouch: " + e.getMessage());
        }
        return null;
    }

    public void verify(String username, VerifyTokenRequest requestBody) {
        Token token = authyClient
                .getTokens()
                .verify(getUserAuthyId(username), requestBody.getToken());

        if(!token.isOk()) {
            logAndThrow("Token verification failed. " + token.getError().toString());
        }
    }

    public boolean retrieveOneTouchStatus(String uuid) {
        try {
            return authyClient
                    .getOneTouch()
                    .getApprovalRequestStatus(uuid)
                    .getApprovalRequest()
                    .getStatus()
                    .equals("approved");
        } catch (OneTouchException e) {
            logAndThrow(e.getMessage());
        }
        return false;
    }

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

    private Integer getUserAuthyId(String username) {
        UserModel user = userRepository.findFirstByUsername(username);
        return user.getAuthyId();
    }
}
Two-Factor Authentication Channels

And there you go, Authy Two-factor Authentication is on and your Java app is protected!

What's Next?

Now that you are keeping the hackers out of this demo app using Two-factor Authentication with Twilio Authy, you can find all of the detailed descriptions for options and API calls in our Authy API Reference. If you're also building a registration flow, also check out our Verify product and the phone verification quickstart which uses this codebase.

For additional guides and tutorials on account security and other products, in Node.js and in our other languages, take a look at the Docs.

 

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.OneTouchException;
import com.authy.api.*;
import com.twilio.accountsecurity.controllers.requests.VerifyTokenRequest;
import com.twilio.accountsecurity.repositories.UserRepository;
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
import com.twilio.accountsecurity.models.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TokenService {

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

    private AuthyApiClient authyClient;
    private UserRepository userRepository;

    @Autowired
    public TokenService(AuthyApiClient authyClient, UserRepository userRepository) {
        this.authyClient = authyClient;
        this.userRepository = userRepository;
    }


    public void sendSmsToken(String username) {
        Hash hash = authyClient
                .getUsers()
                .requestSms(getUserAuthyId(username));

        if(!hash.isOk()) {
            logAndThrow("Problem sending token over SMS. " + hash.getMessage());
        }
    }

    public void sendVoiceToken(String username) {
        UserModel user = userRepository.findFirstByUsername(username);

        Hash hash = authyClient.getUsers().requestCall(user.getAuthyId());
        if(!hash.isOk()) {
            logAndThrow("Problem sending the token on a call. " + hash.getMessage());
        }
    }

    public String sendOneTouchToken(String username) {
        UserModel user = userRepository.findFirstByUsername(username);

        try {
            ApprovalRequestParams params = new ApprovalRequestParams
                    .Builder(user.getAuthyId(), "Login requested for Account Security account.")
                    .setSecondsToExpire(120L)
                    .addDetail("Authy ID", user.getAuthyId().toString())
                    .addDetail("Username", user.getUsername())
                    .addDetail("Location", "San Francisco, CA")
                    .addDetail("Reason", "Demo by Account Security")
                    .build();
            OneTouchResponse response = authyClient
                    .getOneTouch()
                    .sendApprovalRequest(params);

            if(!response.isSuccess()) {
                logAndThrow("Problem sending the token with OneTouch");
            }
            return response.getApprovalRequest().getUUID();
        } catch (OneTouchException e) {
            logAndThrow("Problem sending the token with OneTouch: " + e.getMessage());
        }
        return null;
    }

    public void verify(String username, VerifyTokenRequest requestBody) {
        Token token = authyClient
                .getTokens()
                .verify(getUserAuthyId(username), requestBody.getToken());

        if(!token.isOk()) {
            logAndThrow("Token verification failed. " + token.getError().toString());
        }
    }

    public boolean retrieveOneTouchStatus(String uuid) {
        try {
            return authyClient
                    .getOneTouch()
                    .getApprovalRequestStatus(uuid)
                    .getApprovalRequest()
                    .getStatus()
                    .equals("approved");
        } catch (OneTouchException e) {
            logAndThrow(e.getMessage());
        }
        return false;
    }

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

    private Integer getUserAuthyId(String username) {
        UserModel user = userRepository.findFirstByUsername(username);
        return user.getAuthyId();
    }
}