JavaServer Pages Login Form CAPTCHA Code Example

The JSP Login Form Captcha code example shows how to add BotDetect CAPTCHA protection to a typical JSP login form.

First Time Here?

Check the BotDetect JSP Captcha Quickstart for key integration steps.

To prevent bots from trying to guess the login info by brute force submission of a large number of common values, the visitor first has to prove they are human (by solving the CAPTCHA), and only then is their username and password submission checked against the authentication data store.

Also, if they enter an invalid username + password combination three times, they have to solve the CAPTCHA again. This prevents attempts in which the attacker would first solve the CAPTCHA themselves, and then let a bot brute-force the authentication info.

To keep the example code simple, the example doesn't access a data store to authenticate the user, but accepts all logins with usernames and passwords at least 5 characters long as valid.

Download the BotDetect Java CAPTCHA Generator archive to run this example

Within this page, the root folder of the extracted archive is referred as the <BDC-DIR>.

This example is in the <BDC-DIR>/examples/t_api-captcha-jsp2-login-form/ folder; and contains the following files:

Running Example

This example's war file (in BotDetect download package) already embeds all dependencies.

In case you are making this example from scratch in your IDE, you need to ensure botdetect.jar, botdetect-servlet.jar, and botdetect-jsp20.jar are in the classpath.

index.jsp

<%@page trimDirectiveWhitespaces="true"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="botDetect" uri="https://captcha.com/java/jsp"%>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>BotDetect Java CAPTCHA Validation: JSP Login Form CAPTCHA Code Example</title>
  <link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
  <form method="post" action="loginFormAction" class="column" id="form1">
    <h1>BotDetect Java CAPTCHA Validation:<br> JSP Login Form CAPTCHA Code Example</h1>
    <fieldset>
      <legend>CAPTCHA included in JSP form validation</legend>
      
      <div class="input">
        <label for="username">Username:</label>
        <input type="text" name="username" id="username" class="textbox" value="${param.username}" />
      </div>

      <div class="input">
        <label for="Password">Password:</label>
        <% if (request.getAttribute("isLoggedIn") == null) { %>
            <input type="password" name="password" id="password" class="textbox" />
        <% } else { %>
            <input type="text" name="password" id="password" class="textbox" value="${param.password}" />
        <% } %>
      </div>
      
      <label class="incorrect">${messages.loginError}</label>

      <%
        if ((request.getSession().getAttribute("isCaptchaSolved") == null) 
            && (request.getAttribute("isLoggedIn") == null)) {
      %>
          <label for="captchaCode" class="prompt">Retype the characters from the picture:</label>

          <!-- Adding BotDetect Captcha to the page -->
          <botDetect:captcha id="loginCaptcha" 
                userInputID="captchaCode"
                codeLength="4"
                imageWidth="200"
                codeStyle="ALPHA" />

          <div class="validationDiv">
            <input id="captchaCode" type="text" name="captchaCode" />
            <span class="incorrect">${messages.captchaIncorrect}</span>
          </div>
      <%
        }
      %>
      
      <% if (request.getAttribute("isLoggedIn") == null) { %>
          <input type="submit" name="submitButton" id="submitButton" value="Login" />
      <% } else { %>
          <a href="index.jsp">Back to login page.</a>
      <% } %>
    </fieldset>
  </form>
</body>
</html>

The example login form is simple, containing textboxes for username and password input. We add Captcha protection to the form using the standard procedure.

Note that we check for request parameter isCaptchaSolved to only display Captcha protection if it hasn't already been solved.

LoginFormAction.java

package com.captcha.botdetect.examples.jsp.login_form;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.captcha.botdetect.web.servlet.Captcha;

public class LoginFormAction extends HttpServlet {
  
  private HttpSession session;

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    session = request.getSession(true);
    Map<String, String> messages = new HashMap<String, String>();
    request.setAttribute("messages", messages);
    
    boolean isCaptchaSolved = (session.getAttribute("isCaptchaSolved") != null);
 
    // CAPTCHA user input validation
    if (!isCaptchaSolved) {
      Captcha captcha = Captcha.load(request, "loginCaptcha");
      // validate the Captcha to check we're not dealing with a bot
      boolean isHuman = captcha.validate(request.getParameter("captchaCode"));
      if (!isHuman) {
        // Captcha validation failed, show error message
        messages.put("captchaIncorrect", "Incorrect code");
      } else {
        isCaptchaSolved = true;
        session.setAttribute("isCaptchaSolved", true);
      }
    }
    
    // Captcha validation passed, only now do we perform the protected action 
    // (try to authenticate the user)
    if (isCaptchaSolved) {
      // sumbitted login data
      String username = request.getParameter("username");
      String password = request.getParameter("password");

      // check login format
      boolean isValidLoginFormat = validateLogin(username, password);
   
      if (!isValidLoginFormat) {
        // invalid login format, show error message
        messages.put("loginError", "Invalid authentication info");
      }
      
      // authenticate the user
      if (isValidLoginFormat) {
        boolean isAuthenticated = authenticate(username, password);
        if (!isAuthenticated) {
          // failing authentication 3 times shows the Captcha again
          int count = 0;
          if (session.getAttribute("failedAuthCount") != null) {
            count = (Integer) session.getAttribute("failedAuthCount");
          }
          count++;
          if (count > 2) {
            session.removeAttribute("isCaptchaSolved");
            count = 0;
          }
          session.setAttribute("failedAuthCount", count);
          
          messages.put("loginError", "Authentication failed");
        } else {
          request.setAttribute("isLoggedIn", true);
          session.removeAttribute("isCaptchaSolved");
        }
      }
    }
 
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
    dispatcher.forward(request, response);
  }

  private boolean validateLogin(String username, String password) {
    String pattern = "^[a-zA-Z0-9_]+$"; // alphanumeric chars and underscores only
    if ((username != null) && (password != null)) {
      return (username.matches(pattern) && password.matches(pattern));
    } else {
      return false;
    }
  }

  private boolean authenticate(String username, String password) {
    return (username.length() > 4) && (password.length() > 4);
  }
}

We need to include the BotDetect Captcha library, and create a Captcha object with the same id ("loginCaptcha") and userInputID ("captchaCode") values as were used to show the Captcha on the login form.

Since we want to reset the Captcha status after 3 failed authentications, we keep the related counter in the failedAuthCount session value.

This allows us to implement the proper Login form workflow:

  • The user must first solve the Captcha to prove they are human. This keeps the bots away from the authentication code, both conserving its resources and improving its security (since usernames and passwords will not be forwarded to the underlying data store if the Captcha is not solved first).
  • When the user has proven they are human, they get 3 authentication attempts without new Captcha tests, which allows them to remember the right combination in most cases.
  • If the user fails three authentication requests, they are shown a new Captcha which they must solve before continuing. This throttles authentication access, ensuring username + password combinations cannot be brute-forced, while real human users get theoretically unlimited authentication attempts (as long as they don't mind solving further Captchas).

As previously mentioned, the actual authentication code is not implemented, but the example code should demonstrate the underlying principles adequately.

After successful authentication, the example just displays the user input (while a real login form would set an auth cookie and redirect the user to actual functionality).

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <session-config>
    <session-timeout>
      30
    </session-timeout>
  </session-config>
  
  <servlet>
    <servlet-name>BotDetect Captcha</servlet-name>
    <servlet-class>com.captcha.botdetect.web.servlet.CaptchaServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>BotDetect Captcha</servlet-name>
    <url-pattern>/botdetectcaptcha</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>LoginFormAction</servlet-name>
    <servlet-class>com.captcha.botdetect.examples.jsp.login_form.LoginFormAction</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginFormAction</servlet-name>
    <url-pattern>/loginFormAction</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

In WEB-INF/web.xml file we register CaptchaServlet used for BotDetect Captcha requests and register LoginFormAction servlet used for authenticating users.


Please Note

BotDetect Java Captcha Library v4.0.Beta3.7 is an in-progress port of BotDetect 4 Captcha, and we need you to guide our efforts towards a polished product. Please let us know if you encounter any bugs, implementation issues, or a usage scenario you would like to discuss.