JavaServer Faces Login Form CAPTCHA Code Example

The JSF Login Form Captcha code example shows how to add BotDetect CAPTCHA protection to a typical JavaServer Faces 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.

Downloaded Location

The JSF Login Form CAPTCHA Example is included in examples folder of the download package as bdc3-jsf-login-form-captcha-example.war file. Deploying (unpacking) the file will create a standard JSP directory tree.

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="botDetect" uri="botDetect"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<f:view>
  <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
      <title>BotDetect CAPTCHA Login Form JSF Example</title>
      <link rel="stylesheet" href="stylesheet.css" type="text/css">
    </head>
    <body>
      <h:form prependId="false">
        <h1>BotDetect CAPTCHA Login Form JSF Example</h1>
        <fieldset>
          <h:panelGroup rendered="#{loginForm.validation<2}">
            <legend>CAPTCHA included in JSF Login form validation</legend>
          </h:panelGroup>
          <h:panelGroup rendered="#{loginForm.validation==2}">
            <legend>Validation passed!</legend>
          </h:panelGroup>
          <h:panelGrid columns="1">
            <h:outputText value="Username:"/>
            <h:inputText id="userId" value="#{loginForm.userId}"/>

            <h:outputText value="Password:"/>
            <h:inputSecret id="userPass" value="#{loginForm.userPass}" 
                rendered="#{loginForm.validation<2}"/>
            <h:inputText value="#{loginForm.userPass}" 
                rendered="#{loginForm.validation==2}"/>

            <h:panelGroup rendered="#{loginForm.validation<1}">
              <h:outputLabel for="captchaCodeTextBox" 
                  value="Retype the characters from the picture:"/>
              <!-- Adding BotDetect Captcha to the page -->
              <botDetect:jsfCaptcha id="exampleCaptcha" 
                  binding="#{loginForm.captcha}" imageWidth="200"
                  codeLength="4" codeStyle="alpha"/>
              <div class="validationDiv">
                <h:inputText id="captchaCodeTextBox" 
                    value="#{loginForm.captchaCode}"/>
              </div>
            </h:panelGroup>

            <h:commandButton action="#{loginForm.submit}" value="Submit" 
                rendered="#{loginForm.validation<2}"/>
          </h:panelGrid>
          <h:outputLink 
              value="#{facesContext.externalContext.requestContextPath}/
                  faces/index.jsp"
              rendered="#{loginForm.validation==2}">
              Back to login page.</h:outputLink>
          <h:outputText value="#{loginForm.errorMsg}" 
              rendered="#{loginForm.validation<2}" styleClass="incorrect" />
        </fieldset>
      </h:form>
    </body>
  </html>
</f:view>

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 managed bean validation property's value to display parts of the form regarding authentication and Captcha validation status.

LoginForm.java

package botdetect.examples.jsf.login_form.view;

import botdetect.web.jsf.JsfCaptcha;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean(name="loginForm")
@RequestScoped
public class LoginForm {
  private static final int MAX_FAILS = 3;

  private JsfCaptcha captcha;
  private String captchaCode;
  private String userId, userPass;
  private String errorMsg;
  private int validation;
  private HttpSession session;
  private int attempts;

  public LoginForm() {
    FacesContext ctx = FacesContext.getCurrentInstance();
    session = (HttpSession)FacesContext.getCurrentInstance().
        getExternalContext().getSession(true);
    if(ctx.isPostback()){
      loadSessionAttributes();
    } else {
      saveSessionAttributes();
    }
  }

  public JsfCaptcha getCaptcha() {
    return captcha;
  }

  public void setCaptcha(JsfCaptcha captcha) {
    this.captcha = captcha;
  }

  public String getCaptchaCode() {
    return captchaCode;
  }

  public void setCaptchaCode(String captchaCode) {
    this.captchaCode = captchaCode;
  }

  public String getUserId() {
    return userId;
  }

  public void setUserId(String userId) {
    this.userId = userId;
  }

  public String getUserPass() {
    return userPass;
  }

  public void setUserPass(String userPass) {
    this.userPass = userPass;
  }

  public String getErrorMsg() {
    return errorMsg;
  }

  public int getValidation() {
    return validation;
  }

  public void submit(){
    if(validateCaptcha()){
      if(validateLogin()){
        authenticate();
      }
    }
    captchaCode = "";
    saveSessionAttributes();
  }

  private boolean validateCaptcha(){
    if(validation == 0){
      // validate the Captcha to check we're not dealing with a bot
      if(!this.captcha.validate(captchaCode)){
        errorMsg = "Invalid Captcha code!";
        return false;
      }
    }
    validation = 1;
    return true;
  }

  private boolean validateLogin(){
    String pattern = "^[a-zA-Z0-9_]+$"; 

    boolean validLogin = userId.matches(pattern) && 
        userPass.matches(pattern);
    if(!validLogin){
      errorMsg = "Invalid authentication info";
    }
    return validLogin;
  }

  private void authenticate(){
    if(userId.length() > 4 && userPass.length() > 4){
      validation = 2;
      errorMsg = "";
    } else {
      errorMsg = "Authentication failed";
      if(++attempts >= MAX_FAILS){
        attempts = 0;
        validation = 0;
      }
    }
  }

  private void loadSessionAttributes(){
      if(session.getAttribute("LS_attempts") != null){
        attempts = (Integer)session.getAttribute("LS_attempts");
      }
      if(session.getAttribute("LS_validation") != null){
        validation = (Integer)session.getAttribute("LS_validation");
      }
  }

  private void saveSessionAttributes(){
    session.setAttribute("LS_attempts", attempts);
    session.setAttribute("LS_validation", validation);
  }

}

Since we want to reset the Captcha status after 3 failed authentications, we keep the related counter in the LS_attempts 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).

To run this example, botdetect.jar must be in the classpath.

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.