Skip to contentSkip to navigationSkip to topbar
On this page

Java-Spring 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 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(link takes you to an external page), Spring(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 tiny app from big hacking efforts?


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.


Set up the Authy Client on Your Device

set-up-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 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-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 .env. Either source the .env file or otherwise set the ACCOUNT_SECURITY_API_KEY in your environment.

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
export ACCOUNT_SECURITY_API_KEY=ENTER_SECRET_HERE
4

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

try-the-java-spring-authy-two-factor-demo page anchor

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

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 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?

Terms of service

Copyright © 2024 Twilio Inc.