Skip to contentSkip to navigationSkip to topbar
On this page

Java Servlets Quickstart for Twilio Authy Two-factor Authentication


(warning)

Warning

As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.

For new development, we encourage you to use the Verify v2 API.

Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see Migrating from Authy to Verify for SMS(link takes you to an external page).

Adding two-factor authentication is an excellent way to reduce fraud and increase trust from your users. This quickstart guides you through building a Java Servlets(link takes you to an external page) and AngularJS(link takes you to an external page) application that restricts access to a URL. Four Authy API channels are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect a toy app from malicious hackers? Dive in!


Sign Into (or Sign Up For) a Twilio Account

sign-into-or-sign-up-for-a-twilio-account page anchor

Create a new Twilio account (you can sign up for a free Twilio trial), or sign into an existing Twilio account(link takes you to an external page).

Create a New Authy Application

create-a-new-authy-application page anchor

Once logged in, visit the Authy Console(link takes you to an external page). Click on the red 'Create New Application' (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.


Setup the Authy Client on Your Device

setup-the-authy-client-on-your-device page anchor

This Two-factor Authentication demos two channels which require an installed Authy Client to test: Soft Tokens and Push Authentication. 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-and-setup-the-application page anchor

Clone our Java repository locally(link takes you to an external page), 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 .envbefore sourcing it.

In Windows, set the ACCOUNT_SECURITY_API_KEY variable manually.

Add Your Application API Key

add-your-application-api-key page anchor

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

1
# You can get/create one here :
2
# https://www.twilio.com/console/authy/applications
3
ACCOUNT_SECURITY_API_KEY=ENTER_SECRET_HERE

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!


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

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(link takes you to an external page)), and the application is returned a user_id.

Now visit http://localhost:8080/login/index.html(link takes you to an external page) 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 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.

Two-Factor Authentication Channels

two-factor-authentication-channels page anchor
1
package com.twilio.accountsecurity.services;
2
3
import com.authy.AuthyApiClient;
4
import com.authy.OneTouchException;
5
import com.authy.api.ApprovalRequestParams;
6
import com.authy.api.Hash;
7
import com.authy.api.OneTouchResponse;
8
import com.authy.api.Token;
9
import com.twilio.accountsecurity.exceptions.TokenVerificationException;
10
import com.twilio.accountsecurity.models.UserModel;
11
import com.twilio.accountsecurity.repository.UserRepository;
12
import org.slf4j.Logger;
13
import org.slf4j.LoggerFactory;
14
15
import static com.twilio.accountsecurity.config.Settings.authyId;
16
17
public class TokenService {
18
19
private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);
20
21
private AuthyApiClient authyClient;
22
private UserRepository userRepository;
23
24
public TokenService(AuthyApiClient authyClient, UserRepository userRepository) {
25
this.authyClient = authyClient;
26
this.userRepository = userRepository;
27
}
28
29
public TokenService() {
30
this.authyClient = new AuthyApiClient(authyId());
31
this.userRepository = new UserRepository();
32
}
33
34
public void sendSmsToken(String username) {
35
Hash hash = authyClient
36
.getUsers()
37
.requestSms(getUserAuthyId(username));
38
39
if(!hash.isOk()) {
40
logAndThrow("Problem sending token over SMS");
41
}
42
}
43
44
public void sendVoiceToken(String username) {
45
UserModel user = userRepository.findByUsername(username);
46
47
Hash hash = authyClient.getUsers().requestCall(user.getAuthyId());
48
if(!hash.isOk()) {
49
logAndThrow("Problem sending the token on a call");
50
}
51
}
52
53
public String sendOneTouchToken(String username) {
54
UserModel user = userRepository.findByUsername(username);
55
56
try {
57
ApprovalRequestParams params = new ApprovalRequestParams
58
.Builder(user.getAuthyId(), "Login requested for Account Security account.")
59
.setSecondsToExpire(120L)
60
.addDetail("Authy ID", user.getAuthyId().toString())
61
.addDetail("Username", user.getUsername())
62
.addDetail("Location", "San Francisco, CA")
63
.addDetail("Reason", "Demo by Account Security")
64
.build();
65
OneTouchResponse response = authyClient
66
.getOneTouch()
67
.sendApprovalRequest(params);
68
69
if(!response.isSuccess()) {
70
logAndThrow("Problem sending the token with OneTouch");
71
}
72
return response.getApprovalRequest().getUUID();
73
} catch (OneTouchException e) {
74
logAndThrow("Problem sending the token with OneTouch: " + e.getMessage());
75
}
76
return null;
77
}
78
79
public void verify(String username, String token) {
80
Token verificationResult = authyClient
81
.getTokens()
82
.verify(getUserAuthyId(username), token);
83
84
if(!verificationResult.isOk()) {
85
logAndThrow("Token verification failed");
86
}
87
}
88
89
public String retrieveOneTouchStatus(String uuid) {
90
try {
91
return authyClient
92
.getOneTouch()
93
.getApprovalRequestStatus(uuid)
94
.getApprovalRequest()
95
.getStatus();
96
} catch (OneTouchException e) {
97
logAndThrow(e.getMessage());
98
return "";
99
}
100
}
101
102
private void logAndThrow(String message) {
103
LOGGER.warn(message);
104
throw new TokenVerificationException(message);
105
}
106
107
private Integer getUserAuthyId(String username) {
108
UserModel user = userRepository.findByUsername(username);
109
return user.getAuthyId();
110
}
111
}
112

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


Now that you are keeping the hackers out of this demo app using Twilio Authy Two-factor Authentication, you can find all of the detailed descriptions for options and API calls in our Two-factor Authentication API Reference. If you're also building a registration flow, also check out our Phone Verification product and the 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?

Terms of service

Copyright © 2024 Twilio Inc.