# Two-Factor Authentication with Authy, Java and Servlets

> \[!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](/docs/verify/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](https://www.twilio.com/blog/migrate-authy-to-verify).

This [Java Servlets](https://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html) sample application demonstrates two-factor authentication (2FA) using Authy. To run this sample app yourself, [download the code and follow the instructions on GitHub](https://github.com/TwilioDevEd/authy2fa-servlets).

Adding two-factor authentication (2FA) to your web application increases the security of your user's data. [Multi-factor authentication](https://en.wikipedia.org/wiki/Multi-factor_authentication) determines the identity of a user by validating first by logging into the app, and then through their mobile devices using [Authy](https://www.twilio.com/en-us/trusted-activation/verify).

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](https://authy.com).

```java title="Java Application"
package com.twilio.authy2fa;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class App extends AbstractHandler {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        server.setHandler(new App());

        server.start();
        server.join();
    }

    public void handle(String target,
                       Request baseRequest,
                       HttpServletRequest request,
                       HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
    }
}

```

*[See how VMware uses Authy 2FA to secure their enterprise mobility management solution.](https://customers.twilio.com/1143/vmware/?utm_source=docs\&utm_campaign=docs_to_stories)*

## Configure Authy

If you haven't already, now is the time to [sign up for Authy](https://www.twilio.com/login). Create your first application, naming it as you wish. After you create your application, your production API key will be visible on your [dashboard](https://dashboard.authy.com):

![Authy dashboard showing production API key for Mobile SDK Demo.](https://docs-resources.prod.twilio.com/1cbcfb18fc73b81e8ba4a6af4a0ac4be5215576bb0a4b04e1d11a56a1483924d.png)

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](https://github.com/TwilioDevEd/authy2fa-servlets) for more details.

```java title="Configure Authy" description="src/main/java/com/twilio/authy2fa/servlet/RegistrationServlet.java"
package com.twilio.authy2fa.servlet;

import com.authy.AuthyApiClient;
import com.twilio.authy2fa.exception.AuthyRequestException;
import com.twilio.authy2fa.lib.RequestParametersValidator;
import com.twilio.authy2fa.models.User;
import com.twilio.authy2fa.models.UserService;
import com.twilio.authy2fa.lib.SessionManager;
import com.twilio.authy2fa.service.AuthyRequestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/registration")
public class RegistrationServlet extends HttpServlet{

    private final SessionManager sessionManager;
    private final UserService userService;
    private final AuthyRequestService authyRequestService;

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


    @SuppressWarnings("unused")
    public RegistrationServlet() {
        this(
                new SessionManager(),
                new UserService(),
                new AuthyRequestService()
        );
    }

    public RegistrationServlet(SessionManager sessionManager, UserService userService,
                               AuthyRequestService authyRequestService) {
        this.sessionManager = sessionManager;
        this.userService = userService;
        this.authyRequestService = authyRequestService;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.getRequestDispatcher("/registration.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            try {
                int authyId = authyRequestService.sendRegistrationRequest(email, phoneNumber, countryCode);

                userService.create(new User(name, email, password, countryCode, phoneNumber, authyId));

                response.sendRedirect("/login.jsp");
            } catch (AuthyRequestException e) {

                LOGGER.error(e.getMessage());

                request.setAttribute("data", "Registration failed");
                preserveStatusRequest(request, name, email, countryCode, phoneNumber);
                request.getRequestDispatcher("/registration.jsp").forward(request, response);
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}

```

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

## Register a User with Authy

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](https://authy.com).

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.

```java title="Register a User with Authy" description="src/main/java/com/twilio/authy2fa/servlet/RegistrationServlet.java"
// !mark(55,56,57,58,59,60,61,64,65,66,67,68)
package com.twilio.authy2fa.servlet;

import com.authy.AuthyApiClient;
import com.twilio.authy2fa.exception.AuthyRequestException;
import com.twilio.authy2fa.lib.RequestParametersValidator;
import com.twilio.authy2fa.models.User;
import com.twilio.authy2fa.models.UserService;
import com.twilio.authy2fa.lib.SessionManager;
import com.twilio.authy2fa.service.AuthyRequestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/registration")
public class RegistrationServlet extends HttpServlet{

    private final SessionManager sessionManager;
    private final UserService userService;
    private final AuthyRequestService authyRequestService;

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


    @SuppressWarnings("unused")
    public RegistrationServlet() {
        this(
                new SessionManager(),
                new UserService(),
                new AuthyRequestService()
        );
    }

    public RegistrationServlet(SessionManager sessionManager, UserService userService,
                               AuthyRequestService authyRequestService) {
        this.sessionManager = sessionManager;
        this.userService = userService;
        this.authyRequestService = authyRequestService;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.getRequestDispatcher("/registration.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String countryCode = request.getParameter("countryCode");
        String phoneNumber = request.getParameter("phoneNumber");

        if (validateRequest(request)) {

            try {
                int authyId = authyRequestService.sendRegistrationRequest(email, phoneNumber, countryCode);

                userService.create(new User(name, email, password, countryCode, phoneNumber, authyId));

                response.sendRedirect("/login.jsp");
            } catch (AuthyRequestException e) {

                LOGGER.error(e.getMessage());

                request.setAttribute("data", "Registration failed");
                preserveStatusRequest(request, name, email, countryCode, phoneNumber);
                request.getRequestDispatcher("/registration.jsp").forward(request, response);
            }
        } else {
            preserveStatusRequest(request, name, email, countryCode, phoneNumber);
            request.getRequestDispatcher("/registration.jsp").forward(request, response);
        }
    }

    private boolean validateRequest(HttpServletRequest request) {
        RequestParametersValidator validator = new RequestParametersValidator(request);

        return validator.validatePresence("name", "email", "password", "countryCode", "phoneNumber")
                && validator.validateEmail("email");
    }

    private void preserveStatusRequest(
            HttpServletRequest request,
            String name,
            String email,
            String countryCode,
            String phoneNumber) {
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        request.setAttribute("countryCode", countryCode);
        request.setAttribute("phoneNumber", phoneNumber);
    }
}

```

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

## Log in with Authy OneTouch

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.

```java title="Implement One Touch Approval" description="TwilioDevEd/authy2fa-servlets/src/main/java/com/twilio/authy2fa/service/ApprovalRequestService.java"
// !mark(38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93)
package com.twilio.authy2fa.service;

import com.authy.AuthyApiClient;
import com.authy.OneTouchException;
import com.authy.api.ApprovalRequestParams;
import com.authy.api.Hash;
import com.authy.api.OneTouchResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.authy2fa.exception.ApprovalRequestException;
import com.twilio.authy2fa.models.User;
import org.apache.http.client.fluent.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ApprovalRequestService {

    private static final String AUTHY_USERS_URI_TEMPLATE = "%s/protected/json/users/%s/status?api_key=%s";
    private final String authyBaseURL;

    private final ConfigurationService configuration;
    private final AuthyApiClient client;

    public ApprovalRequestService() {
        this.authyBaseURL =  "https://api.authy.com";
        this.configuration = new ConfigurationService();
        this.client = new AuthyApiClient(configuration.authyApiKey());
    }

    public ApprovalRequestService(String authyBaseURL, ConfigurationService configuration, AuthyApiClient client) {
        this.authyBaseURL = authyBaseURL;
        this.configuration = configuration;
        this.client = client;
    }

    public String sendApprovalRequest(User user) {
        if(hasAuthyApp(user)){
            try {
                OneTouchResponse result = sendOneTouchApprovalRequest(user);
                if(!result.isSuccess()) {
                    throw new ApprovalRequestException(result.getMessage());
                }
                return "onetouch";
            } catch (IOException | OneTouchException e) {
                throw new ApprovalRequestException(e.getMessage());
            }
        } else {
            Hash result = sendSMSToken(user);
            if(!result.isSuccess()) {
                throw new ApprovalRequestException(result.getMessage());
            }
            return "sms";
        }
    }

    private boolean hasAuthyApp(User user) {
        ObjectMapper objectMapper = new ObjectMapper();
        String url = String.format(AUTHY_USERS_URI_TEMPLATE,
                authyBaseURL,
                user.getAuthyId(),
                configuration.authyApiKey()
        );
        try {
            String responseBody = Request.Get(url)
                    .connectTimeout(10000)
                    .socketTimeout(10000)
                    .execute().returnContent().asString();
            TypeReference<HashMap<String,Object>> typeRef
                    = new TypeReference<HashMap<String,Object>>() {};
            HashMap<String,HashMap> o = objectMapper.readValue(responseBody, typeRef);

            return (Boolean) ((Map<String, Object>)o.get("status")).get("registered");
        } catch (IOException e) {
            throw new ApprovalRequestException(e.getMessage());
        }
    }

    private OneTouchResponse sendOneTouchApprovalRequest(User user)
            throws IOException, OneTouchException {
        ApprovalRequestParams parameters = new ApprovalRequestParams.Builder(
                Integer.valueOf(user.getAuthyId()),
                "Request login to Twilio demo app")
                .addDetail("email", user.getEmail())
                .build();

        return client.getOneTouch().sendApprovalRequest(parameters);
    }

    private Hash sendSMSToken(User user){
        return client.getUsers().requestSms(Integer.valueOf(user.getAuthyId()));
    }
}
```

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

## Send the OneTouch Request

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.

```java
ApprovalRequestParams parameters = new ApprovalRequestParams.Builder(
  Integer.valueOf(user.getAuthyId()),
  "Request login to Twilio demo app")
  .addDetail("email", "alice@example.com")
  .addDetail("name", "Alice")
  .addHiddenDetail("phoneNumber", "555-5555")
  .build();
```

```java title="Send the OneTouch Request" description="TwilioDevEd/authy2fa-servlets/src/main/java/com/twilio/authy2fa/service/ApprovalRequestService.java"
// !mark(82,83,84,85,86)
package com.twilio.authy2fa.service;

import com.authy.AuthyApiClient;
import com.authy.OneTouchException;
import com.authy.api.ApprovalRequestParams;
import com.authy.api.Hash;
import com.authy.api.OneTouchResponse;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.authy2fa.exception.ApprovalRequestException;
import com.twilio.authy2fa.models.User;
import org.apache.http.client.fluent.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ApprovalRequestService {

    private static final String AUTHY_USERS_URI_TEMPLATE = "%s/protected/json/users/%s/status?api_key=%s";
    private final String authyBaseURL;

    private final ConfigurationService configuration;
    private final AuthyApiClient client;

    public ApprovalRequestService() {
        this.authyBaseURL =  "https://api.authy.com";
        this.configuration = new ConfigurationService();
        this.client = new AuthyApiClient(configuration.authyApiKey());
    }

    public ApprovalRequestService(String authyBaseURL, ConfigurationService configuration, AuthyApiClient client) {
        this.authyBaseURL = authyBaseURL;
        this.configuration = configuration;
        this.client = client;
    }

    public String sendApprovalRequest(User user) {
        if(hasAuthyApp(user)){
            try {
                OneTouchResponse result = sendOneTouchApprovalRequest(user);
                if(!result.isSuccess()) {
                    throw new ApprovalRequestException(result.getMessage());
                }
                return "onetouch";
            } catch (IOException | OneTouchException e) {
                throw new ApprovalRequestException(e.getMessage());
            }
        } else {
            Hash result = sendSMSToken(user);
            if(!result.isSuccess()) {
                throw new ApprovalRequestException(result.getMessage());
            }
            return "sms";
        }
    }

    private boolean hasAuthyApp(User user) {
        ObjectMapper objectMapper = new ObjectMapper();
        String url = String.format(AUTHY_USERS_URI_TEMPLATE,
                authyBaseURL,
                user.getAuthyId(),
                configuration.authyApiKey()
        );
        try {
            String responseBody = Request.Get(url)
                    .connectTimeout(10000)
                    .socketTimeout(10000)
                    .execute().returnContent().asString();
            TypeReference<HashMap<String,Object>> typeRef
                    = new TypeReference<HashMap<String,Object>>() {};
            HashMap<String,HashMap> o = objectMapper.readValue(responseBody, typeRef);

            return (Boolean) ((Map<String, Object>)o.get("status")).get("registered");
        } catch (IOException e) {
            throw new ApprovalRequestException(e.getMessage());
        }
    }

    private OneTouchResponse sendOneTouchApprovalRequest(User user)
            throws IOException, OneTouchException {
        ApprovalRequestParams parameters = new ApprovalRequestParams.Builder(
                Integer.valueOf(user.getAuthyId()),
                "Request login to Twilio demo app")
                .addDetail("email", user.getEmail())
                .build();

        return client.getOneTouch().sendApprovalRequest(parameters);
    }

    private Hash sendSMSToken(User user){
        return client.getUsers().requestSms(Integer.valueOf(user.getAuthyId()));
    }
}
```

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

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.

```java title="Configure OneTouch Callback to validate request" description="src/main/java/com/twilio/authy2fa/servlet/authy/CallbackServlet.java"
// !mark(34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54)
package com.twilio.authy2fa.servlet.authy;

import com.twilio.authy2fa.models.User;
import com.twilio.authy2fa.models.UserService;
import com.twilio.authy2fa.servlet.requestvalidation.AuthyRequestValidator;
import com.twilio.authy2fa.servlet.requestvalidation.RequestValidationResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/authy/callback"})
public class CallbackServlet extends HttpServlet {

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

    private final UserService userService;


    @SuppressWarnings("unused")
    public CallbackServlet() {
        this(new UserService());
    }

    public CallbackServlet(UserService userService) {
        this.userService = userService;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        AuthyRequestValidator validator = new AuthyRequestValidator(
                System.getenv("AUTHY_API_KEY"), request);
        RequestValidationResult validationResult = validator.validate();

        if (validationResult.isValidSignature()) {
            // Handle approved, denied, unauthorized
            User user = userService.findByAuthyId(validationResult.getAuthyId());
            if(user != null) {
                user.setAuthyStatus(validationResult.getStatus());
                userService.update(user);
            }
        } else {

            LOGGER.error("Received Authy callback but couldn't verify the signature");

            response.sendError(403, "Invalid signature");
        }
    }
}

```

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

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

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.

```js title="Poll the server until we see the result of the Authy OneTouch login" description="src/main/webapp/javascript/application.js"
// !mark(39,40,41,42,43,44,45,46,47,48)
$(document).ready(function() {
    $("#login-form").submit(function(event) {
        event.preventDefault();

        var data = $(event.currentTarget).serialize();
        authyVerification(data);
    });

    var authyVerification = function (data) {
        $.post("/login", data, function (result) {
            resultActions[result]();
        });
    };

    var resultActions = {
        onetouch: function() {
            $("#authy-modal").modal({ backdrop: "static" }, "show");
            $(".auth-token").hide();
            $(".auth-onetouch").fadeIn();
            monitorOneTouchStatus();
        },

        sms: function () {
            $("#authy-modal").modal({ backdrop: "static" }, "show");
            $(".auth-onetouch").hide();
            $(".auth-token").fadeIn();
            requestAuthyToken();
        },

        unauthorized: function () {
            $("#error-message").text("Invalid credentials");
        },

        unexpectedError: function () {
            $("#error-message").text("Unexpected error. Check the logs");
        }
    };

    var monitorOneTouchStatus = function () {
        $.post("/authy/status")
            .done(function (data) {
                if (data === "") {
                    setTimeout(monitorOneTouchStatus, 2000);
                } else {
                    $("#confirm-login").submit();
                }
            });
    }

    var requestAuthyToken = function () {
        $.post("/authy/request-token")
            .done(function (data) {
                $("#authy-token-label").text(data);
            });
    }

    $("#logout").click(function() {
        $("#logout-form").submit();
    });
});
```

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

## Check Login Status

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

```java title="Check Login Status" description="src/main/java/com/twilio/authy2fa/servlet/authy/OneTouchStatusServlet.java"
// !mark(30,31,32,33,34,35,36,37)
package com.twilio.authy2fa.servlet.authy;

import com.twilio.authy2fa.lib.SessionManager;
import com.twilio.authy2fa.models.User;
import com.twilio.authy2fa.models.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/authy/status"})
public class OneTouchStatusServlet extends HttpServlet {

    private final SessionManager sessionManager;
    private final UserService userService;

    @SuppressWarnings("unused")
    public OneTouchStatusServlet() {
        this(new SessionManager(), new UserService());
    }

    public OneTouchStatusServlet(SessionManager sessionManager, UserService userService) {
        this.sessionManager = sessionManager;
        this.userService = userService;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        long userId = sessionManager.getLoggedUserId(request);
        User user = userService.find(userId);

        response.getOutputStream().write(user.getAuthyStatus().getBytes());
    }
}

```

Finally, we can confirm the login.

## Finish the 2FA Step

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*.

```java title="Redirect user to the right page based on authentication status" description="src/main/java/com/twilio/authy2fa/servlet/authentication/ConfirmLogInServlet.java"
// !mark(30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58)
package com.twilio.authy2fa.servlet.authentication;

import com.twilio.authy2fa.lib.SessionManager;
import com.twilio.authy2fa.models.User;
import com.twilio.authy2fa.models.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = {"/confirm-login"})
public class ConfirmLogInServlet extends HttpServlet {

    private final SessionManager sessionManager;
    private final UserService userService;

    @SuppressWarnings("unused")
    public ConfirmLogInServlet() {
        this(new SessionManager(), new UserService());
    }

    public ConfirmLogInServlet(SessionManager sessionManager, UserService userService) {
        this.sessionManager = sessionManager;
        this.userService = userService;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        long userId = sessionManager.getLoggedUserId(request);
        User user = userService.find(userId);

        String authyStatus = user.getAuthyStatus();

        // Reset the Authy status
        user.setAuthyStatus("");
        userService.update(user);

        switch (authyStatus) {
            case "approved":
                sessionManager.logIn(request, user.getId());
                response.sendRedirect("/account");
                break;
            case "denied":
                sessionManager.logOut(request);
                request.setAttribute("data", "You have declined the request");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                break;
            default:
                sessionManager.logOut(request);
                request.setAttribute("data", "Unauthorized access");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                break;
        }
    }
}

```

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

## Where to Next?

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

**[Click-To-Call](/docs/voice/sdks/javascript/get-started)**

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