Skip to contentSkip to navigationSkip to topbar
On this page

Two-Factor Authentication with Authy, Java and Servlets


(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).

This Java Servlets(link takes you to an external page) sample application demonstrates two-factor authentication (2FA) using Authy. To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication(link takes you to an external page) determines the identity of a user by validating first by logging into the app, and then through their mobile devices using Authy(link takes you to an external page).

For the second factor, we will validate that the user has their mobile phone by either:

  • Sending them a OneTouch push notification to their mobile Authy app or
  • Sending them a one-time token in a text message sent with Authy via Twilio(link takes you to an external page).

Java Application

java-application page anchor
1
package com.twilio.authy2fa;
2
3
import org.eclipse.jetty.server.Request;
4
import org.eclipse.jetty.server.Server;
5
import org.eclipse.jetty.server.handler.AbstractHandler;
6
7
import javax.servlet.ServletException;
8
import javax.servlet.http.HttpServletRequest;
9
import javax.servlet.http.HttpServletResponse;
10
import java.io.IOException;
11
12
public class App extends AbstractHandler {
13
14
public static void main(String[] args) throws Exception {
15
Server server = new Server(8080);
16
server.setHandler(new App());
17
18
server.start();
19
server.join();
20
}
21
22
public void handle(String target,
23
Request baseRequest,
24
HttpServletRequest request,
25
HttpServletResponse response)
26
throws IOException, ServletException {
27
response.setContentType("text/html;charset=utf-8");
28
response.setStatus(HttpServletResponse.SC_OK);
29
baseRequest.setHandled(true);
30
}
31
}
32

See how VMware uses Authy 2FA to secure their enterprise mobility management solution.(link takes you to an external page)


Configure Authy

configure-authy page anchor

If you haven't already, now is the time to sign up for Authy(link takes you to an external page). Create your first application, naming it as you wish. After you create your application, your production API key will be visible on your dashboard(link takes you to an external page):

Authy API Key.

Once we have an Authy API key, we store it on this .env file, which helps us set the environment variables for our app.

You'll also want to set a callback URL for your application in the OneTouch section of the Authy dashboard. See the project's README(link takes you to an external page) for more details.

src/main/java/com/twilio/authy2fa/servlet/RegistrationServlet.java

1
package com.twilio.authy2fa.servlet;
2
3
import com.authy.AuthyApiClient;
4
import com.twilio.authy2fa.exception.AuthyRequestException;
5
import com.twilio.authy2fa.lib.RequestParametersValidator;
6
import com.twilio.authy2fa.models.User;
7
import com.twilio.authy2fa.models.UserService;
8
import com.twilio.authy2fa.lib.SessionManager;
9
import com.twilio.authy2fa.service.AuthyRequestService;
10
import org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
12
13
import javax.servlet.ServletException;
14
import javax.servlet.annotation.WebServlet;
15
import javax.servlet.http.HttpServlet;
16
import javax.servlet.http.HttpServletRequest;
17
import javax.servlet.http.HttpServletResponse;
18
import java.io.IOException;
19
20
@WebServlet(urlPatterns = "/registration")
21
public class RegistrationServlet extends HttpServlet{
22
23
private final SessionManager sessionManager;
24
private final UserService userService;
25
private final AuthyRequestService authyRequestService;
26
27
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationServlet.class);
28
29
30
@SuppressWarnings("unused")
31
public RegistrationServlet() {
32
this(
33
new SessionManager(),
34
new UserService(),
35
new AuthyRequestService()
36
);
37
}
38
39
public RegistrationServlet(SessionManager sessionManager, UserService userService,
40
AuthyRequestService authyRequestService) {
41
this.sessionManager = sessionManager;
42
this.userService = userService;
43
this.authyRequestService = authyRequestService;
44
}
45
46
protected void doGet(HttpServletRequest request, HttpServletResponse response)
47
throws ServletException, IOException {
48
49
request.getRequestDispatcher("/registration.jsp").forward(request, response);
50
}
51
52
protected void doPost(HttpServletRequest request, HttpServletResponse response)
53
throws ServletException, IOException {
54
55
String name = request.getParameter("name");
56
String email = request.getParameter("email");
57
String password = request.getParameter("password");
58
String countryCode = request.getParameter("countryCode");
59
String phoneNumber = request.getParameter("phoneNumber");
60
61
if (validateRequest(request)) {
62
63
try {
64
int authyId = authyRequestService.sendRegistrationRequest(email, phoneNumber, countryCode);
65
66
userService.create(new User(name, email, password, countryCode, phoneNumber, authyId));
67
68
response.sendRedirect("/login.jsp");
69
} catch (AuthyRequestException e) {
70
71
LOGGER.error(e.getMessage());
72
73
request.setAttribute("data", "Registration failed");
74
preserveStatusRequest(request, name, email, countryCode, phoneNumber);
75
request.getRequestDispatcher("/registration.jsp").forward(request, response);
76
}
77
} else {
78
preserveStatusRequest(request, name, email, countryCode, phoneNumber);
79
request.getRequestDispatcher("/registration.jsp").forward(request, response);
80
}
81
}
82
83
private boolean validateRequest(HttpServletRequest request) {
84
RequestParametersValidator validator = new RequestParametersValidator(request);
85
86
return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
87
&& validator.validateEmail("email");
88
}
89
90
private void preserveStatusRequest(
91
HttpServletRequest request,
92
String name,
93
String email,
94
String countryCode,
95
String phoneNumber) {
96
request.setAttribute("name", name);
97
request.setAttribute("email", email);
98
request.setAttribute("countryCode", countryCode);
99
request.setAttribute("phoneNumber", phoneNumber);
100
}
101
}
102

Let's take a look at how we register a user with Authy.


Register a User with Authy

register-a-user-with-authy page anchor

When a new user signs up for our website, we call this controller, which handles saving our new user to the database as well as registering the user with Authy(link takes you to an external page).

All Authy needs to get a user set up for your application is the email, phone number and country code. In order to do two-factor authentication, we need to make sure we ask for these things at the point of sign up.

Once we register the user with Authy we can get the user's authy_id back. This is very important since it's how we will verify the identity of our User with Authy.

src/main/java/com/twilio/authy2fa/servlet/RegistrationServlet.java

1
package com.twilio.authy2fa.servlet;
2
3
import com.authy.AuthyApiClient;
4
import com.twilio.authy2fa.exception.AuthyRequestException;
5
import com.twilio.authy2fa.lib.RequestParametersValidator;
6
import com.twilio.authy2fa.models.User;
7
import com.twilio.authy2fa.models.UserService;
8
import com.twilio.authy2fa.lib.SessionManager;
9
import com.twilio.authy2fa.service.AuthyRequestService;
10
import org.slf4j.Logger;
11
import org.slf4j.LoggerFactory;
12
13
import javax.servlet.ServletException;
14
import javax.servlet.annotation.WebServlet;
15
import javax.servlet.http.HttpServlet;
16
import javax.servlet.http.HttpServletRequest;
17
import javax.servlet.http.HttpServletResponse;
18
import java.io.IOException;
19
20
@WebServlet(urlPatterns = "/registration")
21
public class RegistrationServlet extends HttpServlet{
22
23
private final SessionManager sessionManager;
24
private final UserService userService;
25
private final AuthyRequestService authyRequestService;
26
27
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationServlet.class);
28
29
30
@SuppressWarnings("unused")
31
public RegistrationServlet() {
32
this(
33
new SessionManager(),
34
new UserService(),
35
new AuthyRequestService()
36
);
37
}
38
39
public RegistrationServlet(SessionManager sessionManager, UserService userService,
40
AuthyRequestService authyRequestService) {
41
this.sessionManager = sessionManager;
42
this.userService = userService;
43
this.authyRequestService = authyRequestService;
44
}
45
46
protected void doGet(HttpServletRequest request, HttpServletResponse response)
47
throws ServletException, IOException {
48
49
request.getRequestDispatcher("/registration.jsp").forward(request, response);
50
}
51
52
protected void doPost(HttpServletRequest request, HttpServletResponse response)
53
throws ServletException, IOException {
54
55
String name = request.getParameter("name");
56
String email = request.getParameter("email");
57
String password = request.getParameter("password");
58
String countryCode = request.getParameter("countryCode");
59
String phoneNumber = request.getParameter("phoneNumber");
60
61
if (validateRequest(request)) {
62
63
try {
64
int authyId = authyRequestService.sendRegistrationRequest(email, phoneNumber, countryCode);
65
66
userService.create(new User(name, email, password, countryCode, phoneNumber, authyId));
67
68
response.sendRedirect("/login.jsp");
69
} catch (AuthyRequestException e) {
70
71
LOGGER.error(e.getMessage());
72
73
request.setAttribute("data", "Registration failed");
74
preserveStatusRequest(request, name, email, countryCode, phoneNumber);
75
request.getRequestDispatcher("/registration.jsp").forward(request, response);
76
}
77
} else {
78
preserveStatusRequest(request, name, email, countryCode, phoneNumber);
79
request.getRequestDispatcher("/registration.jsp").forward(request, response);
80
}
81
}
82
83
private boolean validateRequest(HttpServletRequest request) {
84
RequestParametersValidator validator = new RequestParametersValidator(request);
85
86
return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
87
&& validator.validateEmail("email");
88
}
89
90
private void preserveStatusRequest(
91
HttpServletRequest request,
92
String name,
93
String email,
94
String countryCode,
95
String phoneNumber) {
96
request.setAttribute("name", name);
97
request.setAttribute("email", email);
98
request.setAttribute("countryCode", countryCode);
99
request.setAttribute("phoneNumber", phoneNumber);
100
}
101
}
102

Having registered our user with Authy, we then can use Authy's OneTouch feature to log them in.


Log in with Authy OneTouch

log-in-with-authy-onetouch page anchor

When a User attempts to log in to our website, we will ask them for a second form of identification. Let's take a look at OneTouch verification first.

OneTouch works as follows:

  • We check that the user has the Authy app installed.
  • In case they do, they will receive a push notification on their device.
  • The user hits Approve in their Authy app.
  • Authy makes a POST request to our app with an approved status.
  • We log the user in.

Implement One Touch Approval

implement-one-touch-approval page anchor

TwilioDevEd/authy2fa-servlets/src/main/java/com/twilio/authy2fa/service/ApprovalRequestService.java

1
package com.twilio.authy2fa.service;
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.fasterxml.jackson.core.type.TypeReference;
9
import com.fasterxml.jackson.databind.ObjectMapper;
10
import com.twilio.authy2fa.exception.ApprovalRequestException;
11
import com.twilio.authy2fa.models.User;
12
import org.apache.http.client.fluent.Request;
13
14
import java.io.IOException;
15
import java.util.HashMap;
16
import java.util.Map;
17
18
public class ApprovalRequestService {
19
20
private static final String AUTHY_USERS_URI_TEMPLATE = "%s/protected/json/users/%s/status?api_key=%s";
21
private final String authyBaseURL;
22
23
private final ConfigurationService configuration;
24
private final AuthyApiClient client;
25
26
public ApprovalRequestService() {
27
this.authyBaseURL = "https://api.authy.com";
28
this.configuration = new ConfigurationService();
29
this.client = new AuthyApiClient(configuration.authyApiKey());
30
}
31
32
public ApprovalRequestService(String authyBaseURL, ConfigurationService configuration, AuthyApiClient client) {
33
this.authyBaseURL = authyBaseURL;
34
this.configuration = configuration;
35
this.client = client;
36
}
37
38
public String sendApprovalRequest(User user) {
39
if(hasAuthyApp(user)){
40
try {
41
OneTouchResponse result = sendOneTouchApprovalRequest(user);
42
if(!result.isSuccess()) {
43
throw new ApprovalRequestException(result.getMessage());
44
}
45
return "onetouch";
46
} catch (IOException | OneTouchException e) {
47
throw new ApprovalRequestException(e.getMessage());
48
}
49
} else {
50
Hash result = sendSMSToken(user);
51
if(!result.isSuccess()) {
52
throw new ApprovalRequestException(result.getMessage());
53
}
54
return "sms";
55
}
56
}
57
58
private boolean hasAuthyApp(User user) {
59
ObjectMapper objectMapper = new ObjectMapper();
60
String url = String.format(AUTHY_USERS_URI_TEMPLATE,
61
authyBaseURL,
62
user.getAuthyId(),
63
configuration.authyApiKey()
64
);
65
try {
66
String responseBody = Request.Get(url)
67
.connectTimeout(10000)
68
.socketTimeout(10000)
69
.execute().returnContent().asString();
70
TypeReference<HashMap<String,Object>> typeRef
71
= new TypeReference<HashMap<String,Object>>() {};
72
HashMap<String,HashMap> o = objectMapper.readValue(responseBody, typeRef);
73
74
return (Boolean) ((Map<String, Object>)o.get("status")).get("registered");
75
} catch (IOException e) {
76
throw new ApprovalRequestException(e.getMessage());
77
}
78
}
79
80
private OneTouchResponse sendOneTouchApprovalRequest(User user)
81
throws IOException, OneTouchException {
82
ApprovalRequestParams parameters = new ApprovalRequestParams.Builder(
83
Integer.valueOf(user.getAuthyId()),
84
"Request login to Twilio demo app")
85
.addDetail("email", user.getEmail())
86
.build();
87
88
return client.getOneTouch().sendApprovalRequest(parameters);
89
}
90
91
private Hash sendSMSToken(User user){
92
return client.getUsers().requestSms(Integer.valueOf(user.getAuthyId()));
93
}
94
}

Now let's look at how to send a OneTouch request.


Send the OneTouch Request

send-the-onetouch-request page anchor

When our user logs in, our app decides which two-factor authentication provider will be used. It can be Authy OneTouch or an SMS token.

Authy OneTouch will be used when the user has a registered OneTouch device.

We use the sendApprovalRequest method to create an approval request. It takes an ApprovalRequestParamater object with at least the following properties configured:

  • The Authy user ID.
  • The message that will be displayed in the device.

Here is an example about how to build the parameters object.

1
ApprovalRequestParams parameters = new ApprovalRequestParams.Builder(
2
Integer.valueOf(user.getAuthyId()),
3
"Request login to Twilio demo app")
4
.addDetail("email", "alice@example.com")
5
.addDetail("name", "Alice")
6
.addHiddenDetail("phoneNumber", "555-5555")
7
.build();

TwilioDevEd/authy2fa-servlets/src/main/java/com/twilio/authy2fa/service/ApprovalRequestService.java

1
package com.twilio.authy2fa.service;
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.fasterxml.jackson.core.type.TypeReference;
9
import com.fasterxml.jackson.databind.ObjectMapper;
10
import com.twilio.authy2fa.exception.ApprovalRequestException;
11
import com.twilio.authy2fa.models.User;
12
import org.apache.http.client.fluent.Request;
13
14
import java.io.IOException;
15
import java.util.HashMap;
16
import java.util.Map;
17
18
public class ApprovalRequestService {
19
20
private static final String AUTHY_USERS_URI_TEMPLATE = "%s/protected/json/users/%s/status?api_key=%s";
21
private final String authyBaseURL;
22
23
private final ConfigurationService configuration;
24
private final AuthyApiClient client;
25
26
public ApprovalRequestService() {
27
this.authyBaseURL = "https://api.authy.com";
28
this.configuration = new ConfigurationService();
29
this.client = new AuthyApiClient(configuration.authyApiKey());
30
}
31
32
public ApprovalRequestService(String authyBaseURL, ConfigurationService configuration, AuthyApiClient client) {
33
this.authyBaseURL = authyBaseURL;
34
this.configuration = configuration;
35
this.client = client;
36
}
37
38
public String sendApprovalRequest(User user) {
39
if(hasAuthyApp(user)){
40
try {
41
OneTouchResponse result = sendOneTouchApprovalRequest(user);
42
if(!result.isSuccess()) {
43
throw new ApprovalRequestException(result.getMessage());
44
}
45
return "onetouch";
46
} catch (IOException | OneTouchException e) {
47
throw new ApprovalRequestException(e.getMessage());
48
}
49
} else {
50
Hash result = sendSMSToken(user);
51
if(!result.isSuccess()) {
52
throw new ApprovalRequestException(result.getMessage());
53
}
54
return "sms";
55
}
56
}
57
58
private boolean hasAuthyApp(User user) {
59
ObjectMapper objectMapper = new ObjectMapper();
60
String url = String.format(AUTHY_USERS_URI_TEMPLATE,
61
authyBaseURL,
62
user.getAuthyId(),
63
configuration.authyApiKey()
64
);
65
try {
66
String responseBody = Request.Get(url)
67
.connectTimeout(10000)
68
.socketTimeout(10000)
69
.execute().returnContent().asString();
70
TypeReference<HashMap<String,Object>> typeRef
71
= new TypeReference<HashMap<String,Object>>() {};
72
HashMap<String,HashMap> o = objectMapper.readValue(responseBody, typeRef);
73
74
return (Boolean) ((Map<String, Object>)o.get("status")).get("registered");
75
} catch (IOException e) {
76
throw new ApprovalRequestException(e.getMessage());
77
}
78
}
79
80
private OneTouchResponse sendOneTouchApprovalRequest(User user)
81
throws IOException, OneTouchException {
82
ApprovalRequestParams parameters = new ApprovalRequestParams.Builder(
83
Integer.valueOf(user.getAuthyId()),
84
"Request login to Twilio demo app")
85
.addDetail("email", user.getEmail())
86
.build();
87
88
return client.getOneTouch().sendApprovalRequest(parameters);
89
}
90
91
private Hash sendSMSToken(User user){
92
return client.getUsers().requestSms(Integer.valueOf(user.getAuthyId()));
93
}
94
}

Once we send the request we need to update our user's AuthyStatus based on the response. But first we have to register a OneTouch callback endpoint.


Configuring the OneTouch callback

configuring-the-onetouch-callback page anchor

In order for our app to know what the user did after we sent the OneTouch request, we need to register a callback endpoint with Authy.

Note: In order to verify that the request is coming from Authy, we've written the helper method validate that will halt the request if it appears that it isn't coming from Authy.

Here in our callback, we look up the user using the Authy ID sent with the Authy POST request. Ideally at this point we would probably use a websocket to let our client know that we received a response from Authy. However for this version we're going to just update the AuthyStatus on the User. What our client-side code needs to do is to check for user.AuthyStatus == "approved" before logging them in.

Configure OneTouch Callback to validate request

configure-onetouch-callback-to-validate-request page anchor

src/main/java/com/twilio/authy2fa/servlet/authy/CallbackServlet.java

1
package com.twilio.authy2fa.servlet.authy;
2
3
import com.twilio.authy2fa.models.User;
4
import com.twilio.authy2fa.models.UserService;
5
import com.twilio.authy2fa.servlet.requestvalidation.AuthyRequestValidator;
6
import com.twilio.authy2fa.servlet.requestvalidation.RequestValidationResult;
7
import org.slf4j.Logger;
8
import org.slf4j.LoggerFactory;
9
10
import javax.servlet.ServletException;
11
import javax.servlet.annotation.WebServlet;
12
import javax.servlet.http.HttpServlet;
13
import javax.servlet.http.HttpServletRequest;
14
import javax.servlet.http.HttpServletResponse;
15
import java.io.IOException;
16
17
@WebServlet(urlPatterns = {"/authy/callback"})
18
public class CallbackServlet extends HttpServlet {
19
20
private static final Logger LOGGER = LoggerFactory.getLogger(CallbackServlet.class);
21
22
private final UserService userService;
23
24
25
@SuppressWarnings("unused")
26
public CallbackServlet() {
27
this(new UserService());
28
}
29
30
public CallbackServlet(UserService userService) {
31
this.userService = userService;
32
}
33
34
protected void doPost(HttpServletRequest request, HttpServletResponse response)
35
throws ServletException, IOException {
36
37
AuthyRequestValidator validator = new AuthyRequestValidator(
38
System.getenv("AUTHY_API_KEY"), request);
39
RequestValidationResult validationResult = validator.validate();
40
41
if (validationResult.isValidSignature()) {
42
// Handle approved, denied, unauthorized
43
User user = userService.findByAuthyId(validationResult.getAuthyId());
44
if(user != null) {
45
user.setAuthyStatus(validationResult.getStatus());
46
userService.update(user);
47
}
48
} else {
49
50
LOGGER.error("Received Authy callback but couldn't verify the signature");
51
52
response.sendError(403, "Invalid signature");
53
}
54
}
55
}
56

Our application is now capable of using Authy for two-factor authentication. However, we are still missing an important part: the client-side code that will handle it.


Disabling Unsuccessful Callbacks

disabling-unsuccessful-callbacks page anchor

Scenario: The OneTouch callback URL provided by you is no longer active.

Action: We will disable the OneTouch callback after 3 consecutive HTTP error responses. We will also

  • Set the OneTouch callback URL to blank.
  • Send an email notifying you that the OneTouch callback is disabled with details on how to enable the OneTouch callback.

How to enable OneTouch callback? You need to update the OneTouch callback endpoint, which will allow the OneTouch callback.

Visit the Twilio Console: Console > Authy > Applications > {ApplicationName} > Push Authentication > Webhooks > Endpoint/URL to update the Endpoint/URL with a valid OneTouch callback URL.


Handle Two-Factor in the Browser

handle-two-factor-in-the-browser page anchor

We've already taken a look at what's happening on the server side, so let's step in front of the cameras and see how our JavaScript is interacting with those server endpoints.

When we expect a OneTouch response, we will begin polling /authy/status until we see Authy status is not empty.

Poll the server until we see the result of the Authy OneTouch login

poll-the-server-until-we-see-the-result-of-the-authy-onetouch-login page anchor

src/main/webapp/javascript/application.js

1
$(document).ready(function() {
2
$("#login-form").submit(function(event) {
3
event.preventDefault();
4
5
var data = $(event.currentTarget).serialize();
6
authyVerification(data);
7
});
8
9
var authyVerification = function (data) {
10
$.post("/login", data, function (result) {
11
resultActions[result]();
12
});
13
};
14
15
var resultActions = {
16
onetouch: function() {
17
$("#authy-modal").modal({ backdrop: "static" }, "show");
18
$(".auth-token").hide();
19
$(".auth-onetouch").fadeIn();
20
monitorOneTouchStatus();
21
},
22
23
sms: function () {
24
$("#authy-modal").modal({ backdrop: "static" }, "show");
25
$(".auth-onetouch").hide();
26
$(".auth-token").fadeIn();
27
requestAuthyToken();
28
},
29
30
unauthorized: function () {
31
$("#error-message").text("Invalid credentials");
32
},
33
34
unexpectedError: function () {
35
$("#error-message").text("Unexpected error. Check the logs");
36
}
37
};
38
39
var monitorOneTouchStatus = function () {
40
$.post("/authy/status")
41
.done(function (data) {
42
if (data === "") {
43
setTimeout(monitorOneTouchStatus, 2000);
44
} else {
45
$("#confirm-login").submit();
46
}
47
});
48
}
49
50
var requestAuthyToken = function () {
51
$.post("/authy/request-token")
52
.done(function (data) {
53
$("#authy-token-label").text(data);
54
});
55
}
56
57
$("#logout").click(function() {
58
$("#logout-form").submit();
59
});
60
});

Let's take a closer look at how we check the login status on the server.


This is the endpoint that our JavaScript is polling. It is waiting for the user Authy status.

src/main/java/com/twilio/authy2fa/servlet/authy/OneTouchStatusServlet.java

1
package com.twilio.authy2fa.servlet.authy;
2
3
import com.twilio.authy2fa.lib.SessionManager;
4
import com.twilio.authy2fa.models.User;
5
import com.twilio.authy2fa.models.UserService;
6
7
import javax.servlet.ServletException;
8
import javax.servlet.annotation.WebServlet;
9
import javax.servlet.http.HttpServlet;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12
import java.io.IOException;
13
14
@WebServlet(urlPatterns = {"/authy/status"})
15
public class OneTouchStatusServlet extends HttpServlet {
16
17
private final SessionManager sessionManager;
18
private final UserService userService;
19
20
@SuppressWarnings("unused")
21
public OneTouchStatusServlet() {
22
this(new SessionManager(), new UserService());
23
}
24
25
public OneTouchStatusServlet(SessionManager sessionManager, UserService userService) {
26
this.sessionManager = sessionManager;
27
this.userService = userService;
28
}
29
30
protected void doPost(HttpServletRequest request, HttpServletResponse response)
31
throws ServletException, IOException {
32
33
long userId = sessionManager.getLoggedUserId(request);
34
User user = userService.find(userId);
35
36
response.getOutputStream().write(user.getAuthyStatus().getBytes());
37
}
38
}
39

Finally, we can confirm the login.


If the AuthyStatus is approved , the user will be redirected to the account page, otherwise we'll show the login form with a message that indicates if the request was denied or unauthorized.

Redirect user to the right page based based on authentication status

redirect-user-to-the-right-page-based-based-on-authentication-status page anchor

src/main/java/com/twilio/authy2fa/servlet/authentication/ConfirmLogInServlet.java

1
package com.twilio.authy2fa.servlet.authentication;
2
3
import com.twilio.authy2fa.lib.SessionManager;
4
import com.twilio.authy2fa.models.User;
5
import com.twilio.authy2fa.models.UserService;
6
7
import javax.servlet.ServletException;
8
import javax.servlet.annotation.WebServlet;
9
import javax.servlet.http.HttpServlet;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12
import java.io.IOException;
13
14
@WebServlet(urlPatterns = {"/confirm-login"})
15
public class ConfirmLogInServlet extends HttpServlet {
16
17
private final SessionManager sessionManager;
18
private final UserService userService;
19
20
@SuppressWarnings("unused")
21
public ConfirmLogInServlet() {
22
this(new SessionManager(), new UserService());
23
}
24
25
public ConfirmLogInServlet(SessionManager sessionManager, UserService userService) {
26
this.sessionManager = sessionManager;
27
this.userService = userService;
28
}
29
30
protected void doPost(HttpServletRequest request, HttpServletResponse response)
31
throws ServletException, IOException {
32
33
long userId = sessionManager.getLoggedUserId(request);
34
User user = userService.find(userId);
35
36
String authyStatus = user.getAuthyStatus();
37
38
// Reset the Authy status
39
user.setAuthyStatus("");
40
userService.update(user);
41
42
switch (authyStatus) {
43
case "approved":
44
sessionManager.logIn(request, user.getId());
45
response.sendRedirect("/account");
46
break;
47
case "denied":
48
sessionManager.logOut(request);
49
request.setAttribute("data", "You have declined the request");
50
request.getRequestDispatcher("/login.jsp").forward(request, response);
51
break;
52
default:
53
sessionManager.logOut(request);
54
request.setAttribute("data", "Unauthorized access");
55
request.getRequestDispatcher("/login.jsp").forward(request, response);
56
break;
57
}
58
}
59
}
60

That's it! We've just implemented two-factor auth using three different methods and the latest in Authy technology.


If you're a Java developer working with Twilio, you might enjoy these other tutorials:

Click-To-Call

Click-to-call enables your company to convert web traffic into phone calls with the click of a button.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.